Home > Enterprise >  how to show the background image to a div by using props in react
how to show the background image to a div by using props in react

Time:03-11

I am using react and now I want to add a background image in a div. the image url is coming from props. But the background is not shown the code of the inline css is following

  import React from 'react'
    
    
    export default function City(props) {
      const image = props.img ;      
return (
        <div className='col-lg-4 col-md-4 col-sm-10 ' style={{
          backgroundImage: `url(${image})`}}>
          <p>{image}</p>
        
        </div>
      )
    }

Now what I do to show the background image in a div?

CodePudding user response:

You're almost right, just add the height and width of the div.

function City(props) {
  const image = props.img;
  return (
    <div
      style={{ height:"300px", width:"300px", backgroundImage: `url(${image})` }}
    >
      <p>{image}</p>
    </div>
  );
}
    
    
ReactDOM.render(
  <City img="https://lh3.googleusercontent.com/ogw/ADea4I6PTtu7DPMQ_R27dQUjfvh2Zol_ehq8vIxq8c3DOw=s32-c-mo" />,
  document.body
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

CodePudding user response:

In styled components and material ui libraries you can pass props to styles like so:

Styled Components version:

https://styled-components.com/docs/basics#adapting-based-on-props

Material UI version:

https://mui.com/styles/basics/#adapting-based-on-props

So in the end you can pass your props further to the styles as props.

  • Related