mrpbennett
mrpbennett

Reputation: 1956

Unable to dynamically set a string of text using useState in React

Can anyone advise why this isn't working?

export default function App() {
  const [buttonStatus, setButtonStatus] = useState('rts');
  const [buttonName, setButtonName] = useState('RTS / MPC DSP');

  const switchButtons = (x) => {
    setButtonStatus(x);
  };

  const displayButtons = () => {
    if (buttonStatus === 'rts') {
      setButtonName('RTS / MPC DSP');
      return <RTSButtons />;
    } else if (buttonStatus === 'rtb') {
      setButtonName('RTB');
      return <RTBButtons />;
    } else if (buttonStatus === 'mpc') {
      setButtonName('MPC');
      return <MPCButtons />;
    }
  };

I want to use setButtonName to adjust the name of the button collection here:

<h2 className='font-bold text-2xl capitalize -mb-10 mt-2'>{buttonName}</h2>

But it seems that it either sometimes get just a blank screen when the conditions are met or an infinite loop error message. Is it because I should be doing

return <RTSButtons />, setButtonName('RTS / MPC DSP')

This that is possible?

Upvotes: 1

Views: 49

Answers (1)

Kelvin Schoofs
Kelvin Schoofs

Reputation: 8718

In React, modifying the state (e.g. your setButtonName call) and rendering components (React (indirectly) calling App()) need to be separate. If you try to modify the state during rendering, React will indeed throw an error.

In your case, you can calculate buttomName during rendering, without having to store it in a state variable:

export default function App() {
    const [buttonStatus, setButtonStatus] = useState('rts');
  
    const switchButtons = (x) => {
      setButtonStatus(x);
    };

    let buttonName = 'RTS / MPC DSP';
    let buttons;
    if (buttonStatus === 'rts') {
        buttonName = 'RTS / MPC DSP';
        buttons = <RTSButtons />;
    } else if (etc) {
        // ... etc
    }

    // Example usage
    return <>
        <h2 className='font-bold text-2xl capitalize -mb-10 mt-2'>{buttonName}</h2>
        {buttons}
    </>;
}

Upvotes: 1

Related Questions