How to add background image from local folder to a container

Viewed 175

I want to set the background image of a container div from an image from a local folder. Does anyone know what i need to add to my code/ how to edit it to do this? Currently the image isnt showing for some reason.


class Team extends React.Component{


    render(){

        let style = {
            backgroundRepeat: 'no-repeat',
            backgroundImage:'url("../images/Football_Field.png")',
            backgroundSize: '100% 100%',
            backgroundPosition: 'center',
            width: '100%',
            height: '100%',
            border: '2px dashed #333'
        }

        return (
            <div className="container" style={style}>

                <i className="fas fa-tshirt"></i>
            </div>
        )
    }
}

export default Team

The image is in a 'image' folder inside the src folder. (/src/images/Football_Field.png)

The Team components file path is '/src/components/Team'.

Would anyone also know how to do this if i instead used a ui container class?

3 Answers

You could do something like it in your render method :) Do Know that the path is rooted at the public folder once it's compiled

     render()
    {
        const image = './images/tasse_kandinsky.webp';
        return(
            <div className='product'>
      
                <div className='product-image' style={{backgroundImage: 'url('+image+')'}}>
                    
                </div>
            </div>
        )
    }

Depending on your webpack configuration, you could do something like this:

import backgroundImage from "../images/Football_Field.png";

class Team extends React.Component{
    render(){

        let style = {
            backgroundRepeat: 'no-repeat',
            backgroundImage:'url(' + backgroundImage + ')',
            backgroundSize: '100% 100%',
            backgroundPosition: 'center',
            width: '100%',
            height: '100%',
            border: '2px dashed #333'
        }

        return (
            <div className="container" style={style}>

                <i className="fas fa-tshirt"></i>
            </div>
        )
    }
}

export default Team

Otherwise add your image to your public folder and change the url accordingly.

Related