To display a photo from a URL in React, you can use the standard img
HTML tag and pass the image URL as the src
attribute. Here’s how to do it in a React component:
Example: Displaying an Image from a URL
#react #jsx
import React from "react";
const ImageComponent = () => {
const imageUrl = "https://example.com/path-to-image.jpg"; // Replace with your image URL
return (
<div>
<h2>Displaying Image from URL</h2>
<img src={imageUrl} alt="Description of image" style={{ width: '100%', height: 'auto' }} />
</div>
);
};
export default ImageComponent;
Explain:
- Image URL: Define the image URL (in this case, a placeholder
https://example.com/path-to-image.jpg
). img
tag: Use theimg
tag with thesrc
attribute pointing to the URL. Thealt
attribute provides a description of the image.- Inline Styling: You can add inline styles, such as width and height, to control how the image is displayed. Here, I used
width: '100%'
to make the image responsive.
Dynamic URL from Props:
If you want to dynamically display an image URL passed as a prop, you can modify the component like this:
#react #javascript
import React from "react";
const ImageComponent = ({ imageUrl }) => {
return (
<div>
<h2>Displaying Dynamic Image from URL</h2>
<img src={imageUrl} alt="Dynamic image" style={{ width: '100%', height: 'auto' }} />
</div>
);
};
export default ImageComponent;
You would pass the imageUrl
like this when using the component:
#jsx
<ImageComponent imageUrl="https://example.com/path-to-image.jpg" />
This way, the image URL is flexible and can change based on the props passed into the component.
How Coding Filters Improve Code Efficiency!
Coding filters enhance the efficiency of code by allowing developers to target and process only relevant data. This reduces the need for unnecessary loops, conditional checks, and repetitive logic, leading to faster execution times and optimized resource usage in your applications.