Search code examples
reactjsreact-hooksconditional-rendering

React-Hook conditional rendering (no error, but don't work)


I have have no error in my code. But my condition, finally don't work.

  const togglePeronsHandler = () => {
    const doesShow = personsState.showPersons;
    personsState.showPersons = !doesShow;

    console.log(personsState);
  }

  (...)

  <button className="btn btn-sm btn-primary" 
    onClick={togglePeronsHandler}>Toggle Person
  </button>
  <div className="persons">
      {
       personsState.showPersons === true ?
     (
   personsState.persons.map( (item, index) => (
   <Person name={ item.name }
           index={index}
           age={ item.age }
           click={switchNameHandler}
           changed={nameChangeHandler}/>
  ))
 ) :
 (
   <div className="alert alert-info">No body</div>
 )
} 

When I click on button, personsState.showPersons passed true/false. But rendering it wasn't effect…

At origin, i have change setPersonState but it didn't do anything...


Sandbox : https://codesandbox.io/s/3yn05lro81


Solution

  • Since personsState is immutable, you can't re-assign it. You have to set it with setPersonsState like you did in the other functions.

    I see you need the previous state in order to do that (that's probably where your confusion came from). Apart from the object syntax of setState({...newState}) there is another syntax that takes a callback function: setState(previousState => { return {...newState} }). This is solved using this callback setState syntax.

    This way, your togglePersonsHandler function would look like this:

    const togglePersonsHandler = () => {
      setPersonsState(previousPersonsState => {
        const doesShow = previousPersonsState.showPersons;
        return {
          ...previousPersonsState,
          showPersons: !doesShow
        };
      });
    };
    

    Good luck!