Home > Enterprise >  Return different <Input> in a form using a switch to return the Input
Return different <Input> in a form using a switch to return the Input

Time:11-23

I'm trying to achieve a Form where first you see 2 and then when you click a button, you see other Input. I'm using a switch where based on a value I return the first 2 or the others. I've tried returning only the , returning a form with the inputs but everything gives me the same problem. After i fill the first two text input, when i switch to the others, the first 2 of those input has the values of the previous 2 input.

Thanks for your help.

Here there is a basic version of the code

function renderSwitch() {
  switch (currentPhase) {
    case 0:
      return (
        <div>
          <input name='email' type='email' placeholder='Inserisci email' />
        </div>
      );
      break;

    case 1:
      return (
        <div>
          <input
            name='surname'
            type='text'
            placeholder='Inserisci Cognome...'
          />
        </div>
      );
      break;
  }

  return (
    <div
      className='registerpage'
      style={{ height: '100vh', backgroundColor: 'white' }}
    >
      <div className='formdiv'>
        <form onSubmit={handleSubmit}>
          {renderSwitch()}

          {currentPhase < 1 && (
            <button onClick={() => nextPhase()}>Next</button>
          )}
          {currentPhase > 0 && (
            <button onClick={() => previousPhase()}>Back</button>
          )}
          <br />
          <button type='submit'>Iscriviti</button>
        </form>
      </div>
    </div>
  );
}

CodePudding user response:

You should store the input values using a state:

const [email, setEmail] = useState('')
const [surname, setSurname] = useState('')

function renderSwitch() {
    switch (currentPhase) {
      case 0:
        return (
          <div>
            <input value={email} name='email' type='email' placeholder='Inserisci email' />
          </div>
        );
        break;
  
      case 1:
        return (
          <div>
            <input
            value={surname}
              name='surname'
              type='text'
              placeholder='Inserisci Cognome...'
            />
          </div>
        );
        break;
    }
}

And then reset them once you have submitted your data:

function handleSubmit(e) {
    e.preventDefault()
    // Handler your data...

    setEmail('')
    setSurname('')
}
  • Related