React – How to Add Image in JSX
You can add both local images and external (via URL) images in a React application.
In this tutorial will guide you through different methods of including images in your React components, covering both local images and external resources.
Steps to Add an Image in React
Step 1: For local images, place the image file in your project’s public
folder or the src
folder.
Step 2: Import the image file (if it is in the src
folder) or use a relative path for the public
folder.
Step 3: Use the <img>
tag to display the image, providing the correct src
and alt
attributes.
Example 1: Adding a Local Image
In this example, we will import logo.png
present in the same path as that of App.js
, and use that for image element.
Project Structure:
App.js
import React from 'react';
import logo from './logo.png'; // Import the local image
function App() {
return (
<div>
<h2>Welcome to React Tutorials by TutorialKart.com</h2>
<img src={logo} alt="React Logo" />
</div>
);
}
export default App;
Output
Example 2: Adding an External Image
In this example, we will use an image that is present at specific URL path, and use that for src in image element.
App.js
import React from 'react';
function App() {
return (
<div>
<h1>React with External Image</h1>
<img
src="https://www.tutorialkart.com/img/lion.jpg"
width="300" height="300"
alt="Placeholder Image"
/>
</div>
);
}
export default App;
Output
Explanation
- Local Image: Imported the image using ES6 imports and displayed it using the
<img>
tag. - External Image: Directly used the URL in the
src
attribute of the<img>
tag.
Best Practices
- Always include an
alt
attribute for accessibility and better SEO. - Use optimized images to improve loading performance.
- Organize your image files logically in your project structure.
Conclusion
Adding images to a React application can be done using local files or external URLs. By following these steps and best practices, you can efficiently display images in your React components and enhance the user interface.