reactjsimagesrcreact-image

Dynamic image src linking in react doesn`t work (multiple tries)


In my project I need to link a img src dynamically. This is the whole project structure:

enter image description here

I have tried multiple ways to link up my imag src in the follwing component, as you can see in the out commented part of my code. The path itself cannot be the problem because the third try, which I cannot use cause its not dynamic, works very well.

What am I doin wrong?

import React from 'react';
import * as CommentStyles from './comment.module.scss';
// Only this works
import Image from '../../../../assets/image-anne.jpg';
 
function Comment({comment}) {
    return (
        <div>
            <div className={CommentStyles.firstRow}>
                {/* first try - didn`t work*/}
               {/* <img src={require('../../../../assets/image-anne.jpg')} /> */}
                {/* second try - didn`t work*/}
                {/* <img src={'../../../../assets/image-anne.jpg'}/> */}
                 {/* third try - didn`t work*/}
                <img src='../../../../assets/image-anne.jpg'/>
                {/* fourth try-works: */}
                {/* <img src={Image}/>  */}
                                    
                <div className="firstFlexItem">
                    <div className="name Username">
                        {comment.user.name} <br/>
                        {comment.user.username} 
                    </div>
                </div>

                <p>
                    Reply
                </p>
            </div>
            
        </div>
    )
}

export default Comment


I have now put the jpg in the public folder and it doesn`t work:

enter image description here


Solution

  • I'm assuming you have created your reactjs project using the create-react-app command.

    Since you want to dynamically set the image src attribute, the workaround would be to add the image or images inside the public folder as advised here in the official documentation : https://create-react-app.dev/docs/using-the-public-folder/#when-to-use-the-public-folder

    Then just use

    <img src={`image-anne.jpg`} />
    

    Where src has the path to your image relative to the public folder. This can also be dynamically set and will work just fine

    NOTE : If this doesn't work, use

    <img src={process.env.PUBLIC_URL + '/image-anne.jpg'} /> 
    

    And make sure you kill the current session and restart your app using npm start or yarn start if you still can't see the image.

    Screenshot from above link : enter image description here