0

Need to set a background image from API response in ReactJS

Sample code:

useEffect(() => {
axios.get(`https://apiaddress=${API_KEY}`)
.then(res=>{
    console.log(res);
    setRetrieved(res.data);
    console.log(retrieved);
  
})
.catch(err=>{
    console.log(err)
})
     return(
    <div ClassName="home" style={{backgroundImage:`url({retrieved.imageurl}{/*or 
    any other var of type string*/}), width: 1920, height: 1080 } </div>

Also tried to save the retrieved image in a variable, working fine but the image (which is coming in response) is not rendered as background.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

2

Update your style prop

style={{backgroundImage: `url('${retrieved.imageurl}')`}}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Arfan ali
  • 429
  • 2
  • 5
0

You can try this way if your image comes from an API:

return(
<div ClassName="home" style={{backgroundImage:"url(" + retrieved.imageurl + ")", width: 1920, height: 1080 } </div>

For my answer, I referred to this code answer: Setting a backgroundImage With React Inline Styles

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103