Problem with conditional on React

0

I'm trying to do a conditional where the active component depends on a state variable.

this.state = {
  display: 0,
}

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 can be found at github / cmoutella

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

How can I do this?

    
asked by anonymous 03.12.2018 / 21:52

2 answers

1

The problem is that you should return your element directly. Your render method should look 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 peek at the code when you are already returning some element, but even so, your conditional should return a value. This is why if does not work.

    
03.12.2018 / 22:53
1

You can not place IFs within the scope of 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 the return and assign the return to a variable 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>;
}
    
04.12.2018 / 13:22