Just_Ice
Just_Ice

Reputation: 563

How to create custom checkbox in react hooks

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?".

Upvotes: 1

Views: 5257

Answers (1)

Andres
Andres

Reputation: 1012

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);

Upvotes: 5

Related Questions