0

I ve got a form consisits of two inputs (emain, password) and one checkbox. Code is here:

<Box component="form" onSubmit={handleSubmit} noValidate sx={{ mt: 1 }}>
  <TextField
    margin="normal"
    required
    fullWidth
    id="email"
    label="Email adress"
    name="email"
    autoComplete="email"
    autoFocus
  />
  <TextField
    margin="normal"
    required
    fullWidth
    name="password"
    label="Password"
    type="password"
    id="password"
    autoComplete="current-password"
  />
  <FormControlLabel
    control={<Checkbox value="remember" color="primary" />}
    label="Remember me"
  />
  <Button
    type="submit"
    fullWidth
    variant="contained"
    sx={{ mt: 3, mb: 2 }}
  >
    Sign in
  </Button>
</Box>

To get the values of Email and Password I use smth.like:

  const handleSubmit = (event) => {
    event.preventDefault();
    const data = new FormData(event.currentTarget);
    console.log({
      email: data.get('email'),
      password: data.get('password'),
    });
  };

But what's the best practice to get the value of checkbox "Remember me" (in FormControlLabel)? Of course, I can make a new function to handle the changes of checkbox like:

<FormControlLabel
 control={<Checkbox value="remember" color="primary" />}
 onChanges = {newFunction}
 label="Remember me"
/>

But I think that's it's not a good idea, because I don't need to get all the changes of this checkbox, I just need to know the value of this checkbox in the moment of submitting the form.

3
  • 4
    Add a name to the checkbox, that way it should be part of the formdata. Commented Apr 3, 2022 at 13:46
  • I've added name='remember' to FormControl jsx-tag. And I've added checkbox: data.get('remember') in handleSubmit. Is it a kind of good practice? Commented Apr 3, 2022 at 13:59
  • Sure, why not? Although I always prefer controlled inputs, where each value has a corresponding state. Commented Apr 3, 2022 at 14:40

2 Answers 2

1

As you pointed out, you can make the checkbox controlled with a React state, but it's not needed if you are inside a form, since the form owns the info of each input element inside of it, but in order to do that you must set a name attribute on each input element, then you can read the values by instantiating a FormData:

  const handleSubmit = (e) => {
       e.preventDefault();
       const formData = new FormData(e.target);
       const data = formData.entries();
       for (const entry of data) console.log(entry);
  };

A working example here: https://stackblitz.com/edit/react-ictfjr

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I've added name and now if the checkbox is selected, I've got entry, if no there's just no enry
1

You should use Usestate hooks

Handling a multiple CheckBox : Link

      import React, {useState} from 'react'
        
        export default () => {
            const [fName, setfName] = useState('');
            const [lName, setlName] = useState('');
            const [phone, setPhone] = useState('');
            const [email, setEmail] = useState('');
            const [isChecked, setIsChecked] = useState(false);
    
            const handleOnChange = () => {
               setIsChecked(!isChecked);
      };
        
        const submitValue = () => {
            const frmdetails = {
                'First Name' : fName,
                'Last Name' : lName,
                'Phone' : phone,
                'Email' : email
            }
            console.log(frmdetails);
        }
        
        return(
            <>
            <hr/>
 <div className="topping">
        <input
          type="checkbox"
          id="topping"
          name="topping"
          value="Paneer"
          checked={isChecked}
          onChange={handleOnChange}
        />
        Paneer
      </div>
            <input type="text" placeholder="First Name" onChange={e => setfName(e.target.value)} />
            <input type="text" placeholder="Last Name" onChange={e => setlName(e.target.value)} />
            <input type="text" placeholder="Phone" onChange={e => setPhone(e.target.value)} />
            <input type="text" placeholder="Email" onChange={e => setEmail(e.target.value)} />
            <button onClick={submitValue}>Submit</button>
            </>
            )
        }

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.