Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to use the variable declared outside the render function

Tags:

reactjs

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

like image 837
Shyam Avatar asked Jul 31 '26 09:07

Shyam


1 Answers

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.

like image 164
Bojan Ivanac Avatar answered Aug 02 '26 23:08

Bojan Ivanac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!