Reputation: 801
I want to display an image from a URL in React. For example, I want this image
https://images.pexels.com/photos/20787/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=350
to be displayed in a Card body or reactJS. Is it possible to do it or do I have to download it to assets before I can display it? And how to do it?
Upvotes: 44
Views: 214754
Reputation: 369
To solve this;
For local images:
Use an import statement No need to pollute the public folder
import slideImg1 from '../../assets/pexels-pixabay-259915.jpg';
Then use in Jsx like this
const solveLocalImg = () => (
<img src={slideImg1}/>
//or
<div data-src={slideImg1}>
</div>
)
For online images
Use an array
let imgs = [
'https://res.cloudinary.com/stealthman22/image/upload/v1586308024/new-portfolio/hero/time-lapse-photography-of-waterfalls-during-sunset-210186.jpg',
'https://res.cloudinary.com/stealthman22/image/upload/v1586308023/new-portfolio/hero/two-cargo-ships-sailing-near-city-2144905.jpg',
];
const solveOnlineImg = () => (
<div>
<img src={imgs[0]}/>
<img src={imgs[1]}/>
</div>
)
You can use as many images as you like with the second method. It even makes it easy for you to manage your images. Hopefully, soon enough we'd either get a solution that can make us do things how we are used to with just HTML CSS and js
For now, we are stuck with amazing Webpack
Upvotes: 14
Reputation: 1
In the App.js file, write following code:
import React from 'react';
function App() {
return(
<div>
<img src="image-url" alt="image" />
</div>
);
}
export default App;
Upvotes: 0
Reputation: 1097
You can use tag for displaying the image.If the image source is in props/state use <img src={this.props.url}/>
Upvotes: 5
Reputation: 1742
As you do in HTML
import React from "react";
import ReactDOM from "react-dom";
function App() {
return (
<img
src="https://images.pexels.com/photos/20787/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=350"
alt="new"
/>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Upvotes: 60
Reputation: 5546
Yes. it is possible. just use <img />
tag.
<img src="https://images.pexels.com/photos/20787/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=350">
Upvotes: 3