Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
166
rated 0 times [  167] [ 1]  / answers: 1 / hits: 49529  / 7 Years ago, wed, february 15, 2017, 12:00:00

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?


More From » css

 Answers
43

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.


[#58921] Monday, February 13, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
albert

Total Points: 652
Total Questions: 105
Total Answers: 108

Location: Pitcairn Islands
Member since Fri, Oct 15, 2021
3 Years ago
;