frustrated-dev
frustrated-dev

Reputation: 451

How to pass the value of checkbox in react?

God Day, I'm trying to pass a Boolean value of the checkbox using onChange but onChange is already use to toggle the checkbox value. I dont have idea on what will be the other way around. Please guide me Thank you much.

function ExperienceForm() {

  const [postData, setPostData] = useState({intern: ''});
  const dispatch = useDispatch();
  const handleSubmit = (e) => {
      e.preventDefault();

      dispatch(createPost(postData))
}

  const [state, setState] = React.useState({
    intern: false,
  });

  const handleChange = (event) => {
    setState({ ...state, [event.target.name]: event.target.checked });
    console.log(state.intern);
  };
  
  return (
        <form autoComplete="off" noValidate className="form" onSubmit={handleSubmit}>
            
            <FormControlLabel control={
                <Checkbox
                    checked={state.intern}
                    onChange={handleChange ((e) => setPostData({ ...postData, intern: e.target.value }))}
                    name="intern"
                    color="primary"
                    value={state.intern}
                />
                }
                label="Intern"
            /><br/>
            <Button className="button" variant="container" color="primary" size="large" type="submit" block>Submit</Button>

        </form>
    );
}

export default ExperienceForm;

Upvotes: 0

Views: 3431

Answers (1)

Konstantin Modin
Konstantin Modin

Reputation: 1333

I don't see code of your <FormControlLabel /> and <Checkbox /> components, but with regular html input you can do it like this:

import React, { useState } from "react";

function ExperienceForm() {
  const [postData, setPostData] = useState({ intern: false });
  const [state, setState] = useState({ intern: false });

  const handleChange = ({ target }) => {
    setState({ ...state, [target.name]: target.checked });
    setPostData({ ...postData, intern: target.checked });
  };

  return (
    <form autoComplete="off" noValidate className="form">
      <h2>postData.intern: {postData.intern.toString()}</h2>
      <h2>state.intern: {state.intern.toString()}</h2>
      <input
        type="checkbox"
        checked={state.intern}
        onChange={handleChange}
        name="intern"
        color="primary"
        value={state.intern}
      />
      <button type="submit">Submit</button>
    </form>
  );
}

export default ExperienceForm;

Upvotes: 1

Related Questions