Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

managing multiple form variables using useState

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>
  );
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
    })
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading