17

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?

3
  • That should work. What's the issue? Commented Feb 15, 2017 at 21:37
  • Are you asking how to create a static class variable? Commented Feb 15, 2017 at 21:40
  • I don't know what is going on, I'm working on codepen and is not recognizing the styles :( Commented Feb 15, 2017 at 21:41

2 Answers 2

25

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you it works now :), The thing is that it wasn't printing any errors on the console ( im working on codepen)
and does it make any difference if i do it the way you showed me or any the bottom of the page?
@FidelCastro Codepen may be suppressing errors. If you declare the constant outside of the class, it's okay, but I'd recommend declaring a variable at the narrowest scope possible. If there's no need to declare it outside the class, I wouldn't.
5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.