Problem with parole in React

Asked

Viewed 489 times

0

I’m trying to make a condition where the active component depends on a state variable.

this.state = {
  display: 0,
}

The state 0 is the initial state, which is changed when the user clicks a button.

Depending on the button the display variable will change to a value from 1 to 4.

{if (this.state.display == '0') {
      return ()
      } else if (this.state.display == '1') {
        return()
      } else if (this.state.display == '2') {
        return()
      } else if (this.state.display == '3') {
        return()
      } else if (this.state.display == '4') {
        return(
          <Catalogo></Catalogo>
        )} 
    }}

The full code is in github/cmoutella

Error says 'Parsing error: Unexpected token' and points to if.

How can I do this?

2 answers

2

You cannot Co-link IF’s within the scope of the return. If you want to make the logic inside the Return you have to use the ternary condition.

ex:

render() {
  const {display} = this.state;
  return <div>
      {display == 0 && <Component1/>}
      {display == 1 && <Component2/>}
      {display == 2 && <Component3/>}
      {display == 3 && <Component4/>}
  </div>;
}

Or you make the logic before Return and assign the return to a variable that you will return

ex:

render() {
  const {display} = this.state;
  let retorno;
  if (display == 0) {
    retorno = <Component1/>;
  } else if (display == 1) {
    retorno = <Component2/>;
  } else if (display == 2) {
    retorno = <Component3/>;
  } else {
    retorno = <Component4/>;
  }

  return <div>
   {retorno} 
  </div>;
}

1

The problem you must return your element directly. Your method should be something like:

  render(){
    if (this.state.display == '0') {
      return ()
    } else if (this.state.display == '1') {
      return()
    } else if (this.state.display == '2') {
      return()
    } else if (this.state.display == '3') {
      return()
    } else if (this.state.display == '4') {
      return(
        <Catalogo></Catalogo>
      )} 
    }
  }

You only brush the code when it is already returning an element, but even then, your conditional should return a value. So if it doesn’t work.

  • for testing purposes I put to return <div></div> on those who had not yet returned the component, but the error persists. Googling found that React does not support if Else.

  • the updated code: https://github.com/cmoutella/cmoutella.github.io/blob/issues/03/temporario/hinode/src/App.js

Browser other questions tagged

You are not signed in. Login or sign up in order to post.