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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With