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.

2 Answers 2

2

Update your style prop

style={{backgroundImage: `url('${retrieved.imageurl}')`}}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.