Adding style stored in a variable inside React class

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.


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.