Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding style stored in a variable inside React class

I'm trying to use some style inside my React class. I have done it before doing:

<div style={{background: "red"}}></div>

I want to use a variable instead, for example:

<div style={divStyle}></div>

My code looks like:

class HolaMundo extends React.Component {
  const divStyle = {
    color: 'blue',
  };
  render() {
    return(
      <div className="container" style={divStyle}> 
        <h1> Hola {this.props.name}</h1>
      </div>
    );
  }
}

ReactDOM.render(<HolaMundo name="One" />, document.getElementById("app"));

But the styles are not applied. How can I achieve this?

like image 693
Fidel Castro Avatar asked Feb 15 '17 21:02

Fidel Castro


2 Answers

You can't define a constant in the middle of a class, that's invalid syntax. Class bodies, by definition1, can only contain method definitions, static method definitions, and empty statements (;)2. Define the divStyle inside a method:

class HolaMundo extends React.Component {
    render() {
        const divStyle = {
            color: 'blue',
        };

        return (
          <div className="container" style={divStyle}> 
            <h1>Hola {this.props.name}</h1>
          </div>
        );
    }
}

1Per the ECMAScript 2015 Language Specification, Section 14.5 - Class Definitions

2Babel currently supports class properties (with plugins). You can also assign an instance variable through the constructor, with this.style = { ... } and access it anywhere in the class with this.style.

like image 143
Andrew Li Avatar answered Oct 20 '22 22:10

Andrew Li


At the bottom of the page (below the class declaration) you can define a styles object:

 const styles = {
  exampleStyle: {
    backgroundColor: 'red',
  }
};

then pass it into a components style prop:

style={styles.exampleStyle}

I prefer doing it like this as you can then keep all your styles for the component in one object rather than having a styles object for each of your methods in the class.

like image 31
LuckyLukas Avatar answered Oct 20 '22 21:10

LuckyLukas