1

I am trying to create a custom checkbox, so I can add my own styling and all.

import React, { useState } from "react";
import "./checkbox.module.css";
}
export default props => {
  const [isChecked, setIsChecked] = useState(false);

  const toggleCheck = () => {
    setIsChecked(!isChecked);
  };

  return (
    <>
      <span onClick={() => toggleCheck()}>
        <input type="checkbox" checked={isChecked} {...props} />
        <span />
      </span>
    </>
  );
};

from my main file, I am calling this set of functions.

 const handleModifierChange = event => {
    console.log("inside change", event);
    const selectedID = event.target.value;

  };

<Checkbox
  name={modifier.name}
  value={modifier.id}
  onChange={handleModifierChange}
/>

So I want to be able to pass in my onChange prop though to the actual input field but be notified inside the actual handleModifierChange when the checkbox had a change.

I was trying to follow this stackoverflow post, Styling a checkbox in a ReactJS environment

To the answer, someone asked a similar question I am trying to figure out. "Amazing however, I am unable to get the e.target.name or e.target.id while listening to an onChange event. It returns undefined as the input is not in the DOM. So what do we do in that case?".

1 Answer 1

5

So, you probably have a problem because of re-render of you component after state change. You can try to get rid of handling span's onClick, but just call onClick callback in checkbox change handler:

export default ({ onChange, ...checkboxProps }) => {
  const [isChecked, setIsChecked] = useState(false);

  const changeHandler = () => {
    setIsChecked(!isChecked);

    onChange && onChange(event);
  };

  return (
    <>
      <span>
        <input
          type="checkbox"
          checked={isChecked}
          onChange={changeHandler}
          {...checkboxProps}
        />
        <span />
      </span>
    </>
  );
};

You can even pass checkbox value instead of event instance:

  onChange && onChange(isChecked && props.value);
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.