Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display an image which comes back from an axios request (React)?

I'm working on a google maps project with React. I assign an onClick handler the following method:

  getStreetView(lat,lng){
    let url = `https://maps.googleapis.com/maps/api/streetview?size=600x300&location=${lat},${lng}&heading=151.78&pitch=-0.76&key=MYAPIKEY`
    axios.get(url).then(response=>this.setState({image:response.config.url}));
  }

the state = { image: null } is then beeing assigned the url which I later pass on to an image tag to a child component such as <img src={props.image} alt='street view'/>. Everything works like a charm, however I have come across various other solutions such:

function getBase64(url) {
  return axios
    .get(url, {
      responseType: 'arraybuffer'
    })
    .then(response => Buffer.from(response.data, 'binary').toString('base64'))
}

from b4dnewz from the axios documentation. However I can't find a reasonable approach how to display the image in child component with that response type. My question is, is my approach valid? Is there any reasons why I shouldn't be using it like that?

like image 414
Kleo Avatar asked Jun 09 '18 09:06

Kleo


People also ask

How do I display an image backend in React?

To display an image from a local path in React:Download the image and move it into your src directory. Import the image into your file, e.g. import MyImage from './thumbnail. webp' . Set the src prop of the image element to the imported image, e.g. <img src={MyImage} alt="horse" /> .

How do I fetch images from API in React?

To fetch image from API with React, we can use the fetch function. We call fetch with the imageUrl to make a GET request to it. Then we call res. blob to convert the response object to a blob.


1 Answers

If you are getting the image url from api, then your first method is the right approach, but the

Buffer.from(response.data, 'binary').toString('base64'))

method is used when the image itself is received from server as a binary which is converted to base 64 and given to <img>

like image 143
Rohith Murali Avatar answered Sep 28 '22 00:09

Rohith Murali