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?
To use an image as a link in React, wrap the image in an <a> tag or a Link tag if using react router. The image will get rendered instead of the link and clicking on the image will cause the browser to navigate to the specified page. Copied!
To display a image selected from file input in React, we can call the URL. createObjectURL with the selected file object to and set the returned value as the value of the src prop of the img element. We define the img state which we use as the value of the src prop of the img element.
Use onClick event to handle a function that can use to download and print the image.
To display binary data as image in React, we can convert the image's binary data to a base64 URL. Then we can set the src attribute of the img element to the base64 URL. We have the getImg function that makes a GET request to get an image from the imageUrl with fetch . Then we call response.
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With