Home > Blockchain >  How to navigate programmatically is checkbox true
How to navigate programmatically is checkbox true

Time:12-03

It is necessary for me at a choice chekboksom that the Page2 component was drawn. I created a useState where I keep track of the value of the checkbox, but I don't know how to navigate programmatically when the checkbox is selected. How can I do this?

export default function Home() {
  const [checked, setChecked] = useState(false);
  const navigate = useNavigate();
  const handleChange = () => {
    setChecked(!checked);
  };

  return (
    <>
      <input type="checkbox" onChange={handleChange}></input>
    </>
  );
}

CodePudding user response:

const handleChange = () => {
  setChecked(!checked);
  if (!checked) {
    navigate('/')
  }
};

CodePudding user response:

You don't need any state for this, just use the onChange event object. React state updates are asynchronously processed, so trying to enqueue a state update in the handler and navigate based on the updated state won't work.

export default function Home() {
  const navigate = useNavigate();

  const handleChange = (e) => {
    const { checked } = e.target;
    if (checked) {
      navigate("targetPath");
    }
  };

  return (
    <>
      <input type="checkbox" onChange={handleChange}></input>
    </>
  );
}
  • Related