Home > front end >  Unable to display an image using React JS
Unable to display an image using React JS

Time:04-28

I'm starting out with React JS with a code to display a picture, a header tag and an ordered list. Here's the JS code:

import React from 'react'
import ReactDOM from "react-dom"
const test = (
    <div>
        <img src="./balloons.png" width="100px" alt=""/>
        <h1>Names</h1>
        <ol>
            <li>A</li>
            <li>B</li>
            <li>C</li>
            <li>D</li>
        </ol>
    </div>
)

ReactDOM.render(test,document.getElementById("root"))

Here's the index.html part :

<html>
    <head>
        <link rel="stylesheet" href="index.css">
    </head>
    <body>
        <div id = "root"></div>
        <script src = "index.pack.js"></script>
    </body>
</html>

Now, the code runs and displays an output like this in the react app. I can't see the pic I uploaded.Output screen

Here is the folder arrangement in VS Code if it would help:

Folders

Thanks in advance!

CodePudding user response:

If you save the images in the public folder, it works fine

CodePudding user response:

try to import Image and use it in src like that:

import React from 'react'
import ReactDOM from "react-dom"
// try to import image
import YourImageUrl from './balloons.png';

const test = (
    <div>
        <img src="{YourImageUrl}" width="100px" alt=""/>
        <h1>Names</h1>
        <ol>
            <li>A</li>
            <li>B</li>
            <li>C</li>
            <li>D</li>
        </ol>
    </div>
)

ReactDOM.render(test,document.getElementById("root"))

CodePudding user response:

You will have import the image first. Write js code like this

import React from 'react'
import ReactDOM from "react-dom"
import balloons from './balloons.png'
const test = (
    <div>
        <img src={balloons} width="100px" alt=""/>
        <h1>Names</h1>
        <ol>
            <li>A</li>
            <li>B</li>
            <li>C</li>
            <li>D</li>
        </ol>
    </div>
)

ReactDOM.render(test,document.getElementById("root"))
  • Related