use-radio-group { hook 🐠 }
Single state hook to handle radio like components checked state.
Installation
# with npm:
npm add use-radio-group
# with yarn
yarn add use-radio-group
Usage
To use it, import it:
;
useRadioGroup
hook returns array of 2 elements, first being the state of your radio group, second being setChecked method, to update the state.
The state is an array, so when creating your inputs, you should use indexer with key of your choice to refer to current checked/unchecked value:
;
Note that you need to cast the
checked
value to boolean by!!
to avoid react warnings in case the retrived value for the state is undefined (falsy)
The idea behind the hook is that it can be used easly with different grouping components that act as containers for radio-like buttons etc.
Examples
Check our more complex example with buttons on CodeSandbox:
API
// call to get the state - @initial is inital key to be marked as checked.;// checked: {[key: string]: boolean}// setChecked: (key: string | number) => void
MIT License.