How to pass variables to inline css function in React

11,781

Solution 1

You can use es6 backticks and just add use the following code, this refers to the current instance, so this.state is available inside the methods.

const divStyle = {
    background: `rgb(${this.state.r},${this.state.g},${this.state.b})`
};

Solution 2

You can simply add them to the string:

const divStyle = {
    background: "rgb(" + this.state.r + "," + this.state.g + "," + this.state.b + ")"
};
Share:
11,781

Related videos on Youtube

Ján Báťka
Author by

Ján Báťka

Updated on June 04, 2022

Comments

  • Ján Báťka
    Ján Báťka almost 2 years

    I' ve managed to create class in React and wanted to set random generated background to div container. Const variable named divStyle does include CSS function rbg() but I just can't find solution to Pass variables from this.state to that function

    import React from 'react';
    import './ShopItem.css';
    
    class ShopItem extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            r:Math.floor(Math.random() * 256),
            g:Math.floor(Math.random() * 256),
            b:Math.floor(Math.random() * 256)        
        }
    }
    
    componentDidMount() {
        console.log(this.state.r, this.state.g, this.state.b);
    } 
    
    render(){
    
        const divStyle = {
            background: "rgb()"
        };
    
        return(
            <div className="Item" style={divStyle} >
                {console.log("test")}
                {this.props.data}
            </div>
        );
    };
    };
    
    export default ShopItem;