2

Created an app with create-react-app and tailwindcss. I am trying to display local images in my website. I created this folder structure in src: assets/media/images/profile.jpg. The image is not displayed in browser. Here's what I am doing.

Here's the component in src/components/Hero.js:

import ImageOne from '../assets/media/images/profile.jpg';

const Hero = () => {
return (
    <div className="bg-white h-screen flex flex-col justify-center items-center">
        <h1 className="lg:text-9xl md:text-7xl sm:text-5xl text-3xl font-black mb-14">
            Text
        </h1>

        <img class="rounded" src={ImageOne} alt='Profile'/>
        
    </div>
)
}

export default Hero

The image is simply not displayed. Here's what the browser is loading: <img class="rounded" src="/static/media/profile.ba8339ef.jpg" alt="Profile">

Other stackoberflow answers, like React won't load local images, did not help me.

Bogdan Andrei
  • 75
  • 1
  • 10

2 Answers2

2

double-check all instructions in the tailwind guide, make sure you replaced react-scripts start by craco start:

https://tailwindcss.com/docs/guides/create-react-app

in the meantime, have a look at this example repository:

https://github.com/oieduardorabelo/2021-03-18-tailwindcss-and-create-react-app

I created an assets/media/images/profile.jpg and src/components/Hero.js with the same snippet you shared here, and it is working correctly

oieduardorabelo
  • 2,687
  • 18
  • 21
  • I've been following this tutorial since I am new to these technologies: https://www.youtube.com/watch?v=FiGmAI5e91M&t=615s&ab_channel=TraversyMedia, and I have not used ```craco start```. In package.json, scripts, my start looks like this: ```"start": "npm run watch:css && react-scripts start"```, with watch being: ```"watch:css": "postcss src/assets/tailwind.css -o src/assets/main.css"``` – Bogdan Andrei Mar 17 '21 at 20:55
  • Implemented your suggestions, no luck. Pulled the github repo, and I find out that the problem was with the actual file that I was importing :) – Bogdan Andrei Mar 17 '21 at 23:58
2

Move your images folder from src/assets/media/ to public/ and add :

<img class="rounded" src={process.env.PUBLIC_URL + '/images/profile.jpg'} alt='Profile'/>
MB_
  • 1,667
  • 1
  • 6
  • 14
  • Unfortunately this did not work. This is what the browser loads ```Profile```. No image is displayed still. – Bogdan Andrei Mar 17 '21 at 21:20
  • @BogdanAndrei I don't know Tailwind, you should try oieduardobelo's solution, it seems to be the right one. Look here -> https://blog.logrocket.com/create-react-app-and-tailwindcss/ and https://dev.to/shaan71845/setup-your-reactjs-tailwind-css-project-by-creating-a-template-2ifa – MB_ Mar 17 '21 at 21:25