Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

background-image in react component

I'm building a page and I want a material-ui element to have a background image using background-image CSS property. I have googled for it of course, and there are solutions but for some reason I can't see that image.

P.S.1: even changing that MUI element to regular hasn't helped me at all.

P.S.2: when I'm using inside container it shows, but that's not what I want.

UPDATE1: Tried adding height and width to container, still no luck...

import React from 'react';

import Paper from 'material-ui/Paper';

import IconButton from 'material-ui/IconButton';
import ActionHome from 'material-ui/svg-icons/action/home';


const styles = {
    paperContainer: {
        backgroundImage: `url(${"static/src/img/main.jpg"})`
    }
};

export default class Home extends React.Component{
    render(){
        return(
            <Paper style={styles.paperContainer}>

            </Paper>
        )
    }
}
like image 636
Roman Avatar asked Nov 06 '17 20:11

Roman


3 Answers

You have to import the image as the following, using the relative path.

import React from 'react';

import Paper from 'material-ui/Paper';

import IconButton from 'material-ui/IconButton';
import ActionHome from 'material-ui/svg-icons/action/home';

import Image from '../img/main.jpg'; // Import using relative path


const styles = {
    paperContainer: {
        backgroundImage: `url(${Image})`
    }
};

export default class Home extends React.Component{
    render(){
        return(
            <Paper style={styles.paperContainer}>
                Some text to fill the Paper Component
            </Paper>
        )
    }
}
like image 107
Romain Le Qllc Avatar answered Sep 28 '22 14:09

Romain Le Qllc


I've found a fix for my case. Actually setting container height in pixels have helped.

Here's the code:

import React from 'react';


const styles = {
    paperContainer: {
        height: 1356,
        backgroundImage: `url(${"static/src/img/main.jpg"})`
    }
};

export default class Home extends React.Component {
    render() {
        return (
            <div style={styles.paperContainer}>
            </div>
        )
    }
}
like image 28
Roman Avatar answered Sep 28 '22 14:09

Roman


I got this to work for material-ui, where the padding on my parent element was 24px so I added 48px to the width of the background image to make it work...

const styles = {
   heroContainer: {
     height: 800,
     backgroundImage: `url(${"../static/DSC_1037.jpg"})`,
     backgroundSize: 'cover',
     backgroundPosition: 'center',
     width: `calc(100vw + 48px)`,
     margin: -24,
     padding: 24,
   }
  };
<Grid
    container
    direction="column"
    justify="flex-end"
    alignItems="right"
    style={styles.heroContainer} >
    <Grid item>Goes here</Grid>
</Grid>
like image 41
Meli Avatar answered Sep 28 '22 14:09

Meli