This is the react project and the problem is when I open the website on my computer the image doesn’t appear in the browser so I want to know If the problem is in the path of the image or in the extension of the image
the code is in javascript
here’s the path of the file
src
1-components
*Main.js
*Navbar.js
2-images
*reactjs-icon.png
in Navbar.js file :
import React from "react"
export default function Navbar() {
return (
<nav>
<img src="../images/reactjs-icon.png" alt="my"/>
<h3>ReactFacts</h3>
<h4>React Course - Project 1</h4>
</nav>
)
}
in css file
* {
box-sizing: border-box;
}
body {
margin: 0;
}
nav {
display: flex;
align-items: center;
background-color: #21222A;
height: 90px;
padding: 30px 25px;
}
nav > h3, nav > h4 {
margin: 0;
}
nav > img {
height: 30px;
width: 30px;
}
here’s what is appear in the browser
and here’s the files structure
and here’s the files structure
>Solution :
First the conventional way :
In order to access the images directly and use relative paths and for that you need to actually keep your images in public directory.
|-- public
| |-- images
| |-- my_image.png
So in normal scenario where i want to load an image which is present in images folder.
<img src="/images/my_image.png" alt="my image" />
Here the image will get rendered as all files in public are treated statically.
The react way :
In react you may want to render some images which are not present in public folder then you need to import image(s) and in src send the alias or variable.
import logo from'../images/react_logo.png';
class NavBar extends Component {
render() {
return (
<nav className="nav" style={nbStyle}>
<div className="container">
<img src={logo} alt="logo"/>
</div>
</nav>
);
}
}
Now react knows that the image needs to be exposed to public url and will handle the image by making it available .