in app.js I want to display an image.
import React, { Component } from 'react';
import './App.css';
import Image from './components/Image';
import Input from './components/Image';
class App extends Component {
render() {
return (
<div>
<Image
id={1}
src="./components/indice.png"
/>
<img src={require('/components/indice.png')}/>
<Input
id={2}
type="text"
/>
</div>
);
}
}
export default App;
in some posts I have read that you have to put the images in the public folder in others use src={require(path-image.jpg) how is it done? I'm just starting with reactjs.
To display an image in React js, you have two easy ways to do it.
Example 1
We simply have to import the image into our component, ie
With example 1, it really doesn't matter which folder we have the image stored in.
Example 2:
In your case that you have an Image component, you are passing it a src attribute, which I understand that later in that component you will use it to search for the image.
You can make that from the parent component you pass the image as an attribute, that is:
Parent Component
Then in our child component we simply have to fetch the said image by the props .
Here is the code to test.
DEMO
I hope it helped you.
Cheers!!!
In react you can't import anything outside of the src folder.
If you put the images in the public folder, to get the images you must do it this way:
const image = 'images/image.jpg'
being in this way that it is looking for the images folder inside the public folder.
If you want to import them as such and not save the path to a constant, you should put your images folder inside the src folder.
if you want to keep your assets folder in src and also load images dynamically in a component, you can use require.context() . require.context is from webpack
You also have to be careful with the homepage specified in package.json. If you have a ticket:
homepage: /subdomain
, you have to put in your src:
Actually some comments above are wrong. If you can place the image resources inside the public folder, only to call them, you should not place the ../ to leave the directory, you should only place it in a normal way, for example.
Here I import an image that is inside a folder, which is inside public.
(correct way) = { }
(wrong way) = { }