König des Lichts
König des Lichts

Reputation: 23

How to define state in react components?

I am quite new to React and wonder how this should work:

class App extends Component {
> 4 |   state = {
    |         ^
  5 |     bands: [],
  6 |     concerts: []
  7 |   }

here the error message:

ERROR in ./src/App.js
Module build failed: SyntaxError: Unexpected token (4:8)

Edit (the whole component):

import React, { Component } from 'react'

class App extends Component {
  state = {
    bands: [],
    concerts: []
  }
  render() {
    return <div>hei</div>
  }
}

export default App

Some solution to this?

Upvotes: 2

Views: 95

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075587

If the code is really as shown, you're trying to use a language feature ("class fields") that isn't in the language yet, it's still a stage 3 proposal. You need to ensure whatever transpiler you're using handles transpiling that.

If you don't want to use class fields, define your state property in a constructor:

class App extends Component {
  constructor(...args) {
    super(...args);
    this.state = {
      bands: [],
      concerts: []
    };
  }
  render() {
    return <div>hei</div>
  }
}

Upvotes: 3

lilezek
lilezek

Reputation: 7374

One option would be to put the state inside your constructor:

class App extends Component {
  constructor(props) { 
    super(props)
    this.state = {
      bands: [],
      concerts: []
    };
  }
  render() {
    // Here you can access to this.state
    return <div>hei</div>
  }
}

Upvotes: 1

Related Questions