Home > Mobile >  set props.image as background image in react-js
set props.image as background image in react-js

Time:10-10

I'm in react-js. Say I've a child component which gets an image from the parent.

I can display this image in the child component as

<img src={URL.createObjectURL(props.image)}/>

I'm surprised I didn't find a way to set this image as the background of a div (in the child component)

    <div
    style={{ 
      backgroundImage: ???
    }}/>

I really appreciate any suggestion

CodePudding user response:

You probably just forgot to add width and height to the div, so it doesn't display. Or you forgot to put image url inside url() in CSS.

Try:

backgroundImage: `url(${props.image})`, width:"200px", height:"200px"

CodePudding user response:

You dont need to do URL.createObjectURL just props.image should work and to add image in background, use

<div
    style={{ 
      background: `url(${props.image})`
}}></div>

CodePudding user response:

Thanks to @jainChetan81 and @kajgod. However, I found out the solution is:

style={{ 
  background: `url(${URL.createObjectURL(props.image)})`
}}

Just url(${props.image}) doesn't work with me

  • Related