1

Can someone help me why I get the error of ==> Unexpected token, expected ";"

const AppRoot = () => {
  const [tabIndex, setTabIndex] = React.useState(1);
  const handleTabsChange = index => {
    setTabIndex(index);
  };
  this.state={
    backgroundColor: 'black',
    backgroundColor2: 'black',
    pressed: false,
  };
  changeColor(){
    if(!this.state.pressed){
       this.setState({ pressed: true,backgroundColor: 'red', backgroundColor2: 'black'});
    } else {
      this.setState({ pressed: false, backgroundColor: 'black' ,backgroundColor2: 'red'});
    }
  }
Zahren Naa
  • 17
  • 4
  • You're also missing the closing `}`but this may just be a copy paste error – Josh Bonnick Oct 23 '20 at 12:43
  • From what I can see of your code ... AppRoot isn't closed ? ... Beside that why are you using useState AND this.state ? I'm not sur but if your component doesn't extends the React.class you won't be able to use this.state ! – Seba99 Oct 23 '20 at 12:43
  • 1
    you using this in functional component..... – Robert Oct 23 '20 at 12:46
  • Please go through the documentation and check the difference between functional components and class components. There are many SO posts on this too: [When to use ES6 class based React components vs. functional ES6 React components?](https://stackoverflow.com/questions/36097965) – adiga Oct 23 '20 at 12:48
  • Long story short, you are using the function component, and when you are using it along with Hooks you should not use `.SetState()`, instead use a set function in which you are getting a response from `useState()` hook (in your sample you should use `setTabIndex()`). – Mahesh More Oct 23 '20 at 12:57

2 Answers2

1

changeColor needs to be flaged as a function function changeColor() {}
or a variable const changeColor = () => {}

Muhammed Moussa
  • 4,589
  • 33
  • 27
0
  1. Since you are using the react hook, you should use React.useState for all states. (best practice)

So, instead of this.state={...}, you should use React.useState e.g.

const [backgroundColor, setBckgroundColor] = React.useState('black')
const [backgroundColor2, setBckgroundColor2] = React.useState('black')
const [pressed, setPressed] = React.useState(false)

or

const [myState, setMyState] = React.useState({
    backgroundColor: 'black',
    backgroundColor2: 'black',
    pressed: false,
})

  1. You should use an arrow function.
const changeColor = () => {
    if(!this.state.pressed){
       this.setState({ pressed: true,backgroundColor: 'red', backgroundColor2: 'black'});
    } else {
      this.setState({ pressed: false, backgroundColor: 'black' ,backgroundColor2: 'red'});
    }
  }
wangdev87
  • 8,611
  • 3
  • 8
  • 31