1

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?

1
  • One option is to chain ternary operators: x ? a : y ? b : c. Commented Apr 30, 2022 at 12:42

1 Answer 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>
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.