0

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;
1
  • 2
    Why do you have two states that have the same data? Commented Feb 6, 2021 at 19:16

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

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.