javascriptcssreactjsreact-bootstrapsinglepage

React.Js Background Image properly displayed with words over the top


I'm basically trying to copy this website as a lesson to teach myself React.

http://www.milkbardigital.com.au/#home

Could someone help me to use an image as background and place the text over it, also, how to make it display on the same amount of height on the page?

Here's my current code

import React from 'react';
import {Image} from 'react-bootstrap';

export default React.createClass ( {
    render() {
        var background = {backgroundSize : 'cover'};
        return (
            <div style={{width: 'auto'}}>
                <Image style = {background} responsive src = "http://www.milkbardigital.com.au/wp-content/uploads/2015/11/Milkbar-Home-Background.jpg">
                    This is a test
                </Image>
            </div>
        );
    }
});

Really appreciate the help!


Solution

  • The issue you are facing is that Image component is a void element tag and can't receive a children or a dangerouslySetInnerHTML function.

    You will need to use CSS and a text (or div) element outside of the Image component, like the following:

    var App = React.createClass ( {
        render() {
            var background = {backgroundSize : 'cover'};
            var textStyle = {
              position: 'absolute', 
              top: '50%', 
              left: '50%'
            };
    
            return (
                <div style={{width: 'auto'}}>
                    <Image 
                      style={background} responsive 
                      src="http://www.milkbardigital.com.au/wp-content/uploads/2015/11/Milkbar-Home-Background.jpg">
                    </Image>
                    <h1 style={textStyle}>Text over image</h1>
                </div>
            );
        }
    });
    

    Here is a sample demo: https://codesandbox.io/s/w1W8v3y8

    Hope it helps!