Reputation: 5497
why is that when we declare a object outside the render function and using it in the return of the render function of a component causes an unexpected token error . If i declare the myStyle object inside the render function the below code works correctly.
import React , { Component } from 'react';
class Test extends Component {
var myStyle={
backgroundColor:"red",
width:"100px",
height:"100px",
margin:"0 auto",
marginTop:"50px"
};
render(){
return(
<div style={myStyle}>
</div>
);
}
}
export default Test;
Thanks
Upvotes: 3
Views: 2946
Reputation: 1180
First, since you're using ES6 class syntax, you should use const
or let
to define your variables.
The best solution for you though would be to set the variable into the state of the component. So you can manipulate the state easily later and rerender the component when needed with this.setState();
.
You would do it like this:
Inside the constructor method you would do -
constructor(props){
super(props);
this.state = {
myStyle: {
backgroundColor:"red",
width:"100px",
height:"100px",
margin:"0 auto",
marginTop:"50px"
}
}
}
After that, you can use the ES6 spread operator to apply the CSS to whatever component you like, easily.
Upvotes: 3