Home > other >  managing multiple form variables using useState
managing multiple form variables using useState

Time:02-19

I want to manage multiple form variables such as name and email in one useState although I am not getting any error with the following code, but i am unable to type anything. I am sure something is wrong with my handleChange function but unable to figure it out. Thanks.

import * as React from 'react';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import { useState } from 'react'

export default function BasicTextFields() {

    const [info, setInfo] = useState({
        name: "",
        email: ""
    })

    const handleChange = e => {
        e.persist()
        setInfo({
            ...info,
            [e.target.name]:(e.target.value)
        })
     }

  return (
    <Box
      component="form"
      sx={{
        '& > :not(style)': { m: 1, width: '25ch' },
      }}
      noValidate
      autoComplete="off"
    >
      <TextField 
        id="outlined-basic" 
        label="Name" 
        variant="outlined" 
        value={info.name}
        onChange={handleChange}
        />
        <p>{info.name}</p>
      <TextField 
        id="filled-basic" 
        label="Email" 
        variant="filled" 
        value={info.email}
        onChange={handleChange}
        />
    </Box>
  );
}

CodePudding user response:

I think it's because tou didn't give a name attribute to your inputs. you need to add name="name" and name="email" to your inputs. Also you can tidy your handleChange a bit

const handleChange = e => {
    setInfo({
        ...info,
        [e.target.name]: e.target.value
    })
}
  • Related