Home > database >  Converting useState to a class component
Converting useState to a class component

Time:10-01

Trying to add a login page to my existing react app. Was following along this tutorial https://www.digitalocean.com/community/tutorials/how-to-add-login-authentication-to-react-applications

Got stuck in step 1, because we can’t use hooks in class components. My app is a class component.

So, I was wondering how can I create an equivalent to this in class component?

  const [token, setToken] = useState();

if(!token) {
    return <Login setToken={setToken} />
  }

I've tried this. I'm a newbie in react.

this.state = {
token: null
}

newToken = (e) => {
    this.setState({token: e})
  }
    
  if (!this.state.token) {
    return <Login onChange={this.newToken} />
  }

CodePudding user response:

The class component equivalent to the code you provided is:

class Example extends React.Component {
  state = {
    token: undefined, // Not strictly necessary, as it will be undefined even if you leave this line out
  }

  render() {
    const { token } = this.state;
    if (!token) {
      return <Login setToken={(newToken) => this.setState({ token: newToken })} />
    }
  }
}
  • Related