Skip to main content
Version: 5.7.3

useSelectableList

About​

Easily select a single value from a list of values. very useful for radio buttons, select inputs etc.

Installation​

npm install --save rooks

Importing the hook​

import { useSelectableList } from "rooks";

Usage​

function Demo() {
const [total, setTotal] = useState(0);
const [
selection,
{ matchSelection, toggleSelection, updateSelection }
] = useSelectableList(toppings, 0);

useEffect(() => {
setTotal(selection[1].price);
}, [selection]);

return (
<div className="App">
<h3>useSelectableList Example</h3>
<ul className="toppings-list">
{toppings.map(({ name, price }, index) => {
return (
<li key={index}>
<div className="toppings-list-item">
<div className="left-section">
<input
type="checkbox"
id={`custom-checkbox-${index}`}
name={name}
checked={matchSelection({ index })}
onChange={() => toggleSelection({ index })()}
/>
<label htmlFor={`custom-checkbox-${index}`}>{name}</label>
</div>
<div className="right-section">{price}</div>
</div>
</li>
);
})}
<li>
<div className="toppings-list-item">
<div className="left-section">Total:</div>
<div className="right-section">{total}</div>
</div>
</li>
</ul>
</div>
);
}

render(<Demo />);

Arguments​

Argument valueTypeDescriptionDefault value
listArrayA list of items of any type[]
initialIndexnumberIndex of the initially selected item0
allowUnselectedbooleanWhether to allow unselect when update selectionfalse

Returns​

Returns an array of following items:

Return valueTypeDescription
selectionArrayThe first item is the selected index, the second item is the selected value
methodsObjectObject with methods to control the selectable list, see the table below

Methods:

MethodsTypeDescription
matchSelection({ index?: number, value?: T }) => Booleanreturns true if the item is selected
toggleSelection({ index?: number, value?: T }) => () => voidreturns a function to toggle an item by index or value
updateSelection({ index?: number, value?: T }) => () => voidreturns a function to update specified item

Codesandbox Examples​

Basic Usage​

Join Bhargav's discord server​

You can click on the floating discord icon at the bottom right of the screen and talk to us in our server.