How to change CSS root variable in React?

15,013

Solution 1

Finally found solution

constructor(props){
    super(props);
    this.state = {color: '#3C454B'};
}
changeTheme(e){
    this.setState({color: event.target.value});
    document.documentElement.style.setProperty('--base',this.state.color);
}

class App extends React.Component {
    render() {
        return (
            <div className="row">
                <div className="col-xs-12 text-center">
                    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Aliquam voluptates ut eaque, voluptatum veniam nostrum sequi numquam sint, excepturi amet unde quis, ipsum ducimus reprehenderit eligendi pariatur animi esse sed.</p>
                    <input 
                      className="" 
                      type="color" 
                      defaultValue={this.state.color}
                      onChange={(e) => this.handleColor(e)}
                      />
                    <br/><br/>
                </div>
            </div>
        );
    }
}

ReactDOM.render(<App />, window.document.getElementById('myDiv'));

Solution 2

I found out that you can change the root variable from any element. By wrapping the variable in double quotes "--base" and using it as the key in your style object.

<input 
    className="" 
    type="color" 
    onChange={this.changeTheme.bind(this)}
    style={{"--base":this.state.color}}
/>

Solution 3

I found this answer for you: https://stackoverflow.com/a/37802204 document.documentElement.style.setProperty('--your-variable', '#YOURCOLOR');

Share:
15,013
Mo.
Author by

Mo.

Every nice creation start from imagination followed by dedication. Contacts 👇 Portfolio LinkedIn

Updated on June 17, 2022

Comments

  • Mo.
    Mo. almost 2 years

    Is it possible to change CSS :root variable in ReactJS ? looking for solution to change --basecolor code based on what user selected from .change-me input color

    Demo: https://codepen.io/anon/pen/RgXBEK

    CSS

    :root {
      --base: $primary;
    }
    

    React

    changeTheme(e){
        console.log(e.target.value);
    }
    
    class App extends React.Component {
        render() {
            return (
                <div className="row">
                    <div className="col-xs-12 text-center">
                        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Aliquam voluptates ut eaque, voluptatum veniam nostrum sequi numquam sint, excepturi amet unde quis, ipsum ducimus reprehenderit eligendi pariatur animi esse sed.</p>
                        <input 
                          className="" 
                          type="color" 
                          onChange={this.changeTheme.bind(this)}
                          />
                        <br/><br/>
                    </div>
                </div>
            );
        }
    }
    
    ReactDOM.render(<App />, window.document.getElementById('myDiv'));