Styling React components with a const

Styling React components with a const
0

#1

I keep getting an “unexpected token” but I can´t see anything wrong with my code. Any ideas?


#2

I’m not sure but you’re treating your Button react component as a button html element.

Provide more details on the error and paste link to your project.


#3

Thanks for the answer. But the style is on the div, so it shouldn´t matter the rest I think?


#4

You can not declare variables in your class like that. Classes contain methods. Why not create a state property for the div style?


#5

Oh, sorry!
Failed to compile.

./src/App.js
  Line 12:  Parsing error: Unexpected token

  10 |   }
  11 |
> 12 | const style = {
     |       ^
  13 |   display:"flex"
  14 | }
  15 |

That´s the error.


#6

Like:

  constructor(props) {
    super(props);
    this.state = {
      value: [],
      divStyle: {
        display: "flex"
      }
    };
  }
render() {
    return(
    <div style={this.state.divStyle} id="container">

#7

You were absolutely right! The problem was that I was declaring the variable inside the class. Moved it out and it worked!


#8

Depending on what version of Babel you are using, I think it supports class variable/properties without the const like:

Style = {
  display: "flex"
}

It is transpiled, because the latest version of JavaScript does not allow built-in class variables. What the above basically transpiles to is:

  constructor(props) {
    super(props);
    this.state = {
      value: []
    };
    this.Style = {
        display: "flex"
    };

which means, you could have written the following instead of putting Style into the state property as I first stated.

  constructor(props) {
    super(props);
    this.state = {
      value: []
    };
    this.Style: {
      display: "flex"
    };
  }

#9

Thanks for the complete explanation. I´m still getting used to the Javascript OOP.