. Advertisement .
..3..
. Advertisement .
..4..
If you are confused with the problem import and use an image in a React component and don’t know how to do it, let’s follow this article. We will give you some solutions to handle this problem.
What Can We Do To Import And Use An Image In A React Component?
Solution 1: Utilize the import statement
Utilizing the import statement is the simplest solution to import an image that is locally stored in React component. Let’s look at how the image might be used when it is locally saved through this example:
import Logo from "../src/Reactlogo.jpg";
class App extends Component {
render() {
return <img src={Logo} />
}
}
In this case, we continue to use the src property of the <img> element (we should not be mistaken it with the folder). At this time, the src attribute’s value is a Logo variable instead of a string, as it was the last time.
Because of this reason, to read its value, we must utilize curly brackets. Curly braces are used in JSX to consider an expression as valid JavaScript code and to read the JavaScript variables’ value.
You are free to import as many pictures as you want, but you must give them unique names in the import statement.
Solution 2: Utilize the require() function
Similar to the import statement, the require() method enables you to contain the external modules from external files.
Let’s see how to feature the same image from the earlier examples using require() through the following example:
let Logo = require('./images/react-logo.png');
const App = () => {
return (
<div>
<img src={Logo} alt="React Logo" />
</div>
);
};
Although the syntax of the require() function is slightly different with the import statement’s, it is clear that the effect of require() function like the import statement’s. The function requires one argument, the relative path of the image.
Unlike the import statement, the require() function can also be used as an inline value. Take a look at the following instance to understand more:
const App = () => {
return (
<div>
<img src={require('./images/react-logo.png')} alt="React Logo" />
</div>
);
};
Solution 3: Utilize the image link
Let’s begin with the simplest situation, displaying the images uploaded externally utilizing their link. Take a look at this example:
class App extends Component {
render() {
return <img src="https://reactjs.org/logo-og.png" />
}
}
In the above example, an <img> element is returned by our simple app component. To specify the link to the image, we utilize the src attribute.
Conclusion
We believe that with the above solutions, you can quickly import and use an image in a React component. If you have any other questions or concerns about this issue, please leave a comment below. Thank you for reading; we are always excited when one of our posts can provide helpful information on a topic like this!
Read more
Leave a comment