How to display background Image in React inline style
I am trying to set background image for my div through inline style property backgroundImage in React. I get the URL for my image in props. But the image was not displayed Following is my code
const category = ({title,urlImage}) => { <div style = {{ backgroundImage: `url(${urlImage})` }} > {title} </div>
Above code was not working then after searching on stackoverflow i found a method using require but when i use require it gives Error: Cannot find module ‘Image Path’. I used require as following
const category = ({title,urlImage}) => { <div style = {{ backgroundImage: 'url(' + require(`${urlImage}`) + ')' }} > {title} </div>
Could anyone please help me in this
First of all, you have to name your component with a capital letter. Secondly, I guess that you just need to add height to your div.
I think background Image is being loaded but as the div is not containing anything, so the height and width of the div is 0px. Also the name of your component is in SmallCase. You need to capitalize it.
In that case change the div:
From
const category = ({title,urlImage}) => { <div style = {{ backgroundImage: `url(${urlImage})` }} > {title} </div>
To
const Category = ({title,urlImage}) => { <div style = {{ height: '100px'; //change according to your desired design width: '100px';//change according to your desired design backgroundImage: `url(${urlImage})` }} > {title} </div>
Update
const Category = ({title,urlImage}) => { <div style = {{ height: '100px', //change according to your desired design width: '100px',//change according to your desired design backgroundImage: `url(${urlImage})` }} > {title} </div>