Search code examples
reactjseventsreact-hooksstate

Conditional render with the hook: UseState


I'm junior developer whose main task is to develop a event that change into another event when you click a button. Kinda this:

enter image description here

In step, this is how I did and it didnt work:

enter image description here

I wanna know how can I conditional render both component in order change one after another how the first gif implies?

This is my code:

function Event(props) {
  return (
    <>
      <h1> Nueva carga de archivo...</h1>
      <p class="Message"> Nueva base de datos Jun22xls</p>
      <progress value="10" max="100">
        75%
      </progress>
    </>
  );
}

function eventUpdated(props) {
  return <h1>Archivo Cargado exitosamente</h1>;
}

function Progressbar(props) {
  const [state, setNewState] = useState(true);
  const isLoggedIn = props.isLoggedIn;

  const HandleLogin = useCallback(() => {
    setNewState((prevstate) => ({ state: !state.prevstate }));
  }, []);

  return (
    <div class="Container">
      {state ? <Event /> : <eventUpdated />}
      <AiOutlineCloseCircle className="close-icon" onClick={HandleLogin} />
    </div>
  );
}

If anyone could provide me so useful help or advice; I'd really be grateful.

Thanks and have a nice nice day!


Solution

  • The way you use the setNewState is not correct, you should do :

    const HandleLogin = useCallback(() => {
        setNewState((prevstate) => !prevstate);
      }, []);
    

    state.prevstate would assume that your state is an object with the attribute prevstate but your state is boolean.

    prevstate is already your previous state so if prevstate is true returning !prevstate would update the state to false.

    Check the doc here : https://reactjs.org/docs/hooks-reference.html#functional-updates