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?
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" /> .
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.
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>
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