'How to toggle between 3 elements in React?
The landing page in my app has 2 states: sign_in
and sign_up
: const [loginForm, setLoginForm] = useState(true);
In my JSX I have:
return (
<LoginFormContainer>
<LoginCheckBody />
{loginForm ?
// stuff when sign_in form should show
:
// stuff when sign_up form should show
}
</LoginFormContainer>
)
In the stuff when
I have buttons to switch the loginForm
state. Now I want to add a third option: forgot_password
.
I have to change to the loginForm
to a string and instead of passing booleans, pass string values. But I wondering how to resolve that in the JSX. Now I'm using a ternary condition to toggle between 2 states but that won't work.
I kinda want to use a switch to display a form corresponding to the set value of loginForm
. Any suggestions?
Solution 1:[1]
To restrict values on your states, I'd suggest that you should have a constant variable to keep your state values
const FORM_STATE = {
signIn: 'sign_in',
signUp: 'sign_up',
forgotPassword: 'forgot_password'
}
And then you just need to modify your state like below
const [form, setForm] = useState(FORM_STATE.signIn); //login state as default
Note that I modified loginForm
to form
because of state name alignment
Here is how you change states
setForm(FORM_STATE.signUp) //state values are from FORM_STATE
For the rendering part, you can do it this way
return (
<LoginFormContainer>
<LoginCheckBody />
{form === FORM_STATE.signIn && <div>Login</div>}
{form === FORM_STATE.signUp && <div>Sign up</div>}
{form === FORM_STATE.forgotPassword && <div>Forgot password</div>}
</LoginFormContainer>
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nick Vu |