2.0.2 • Published 4 years ago
use-toggle-button-group-state v2.0.2
use-toggle-button-group-state
React hook managing the state of a toggle button group. A toggle group is used to group related options under a common container. Only one option in a group of buttons can be selected and active at a time. Selecting one option deselects any other. It strictly acts like a radio-button group. the toggle group state makes it clear which button is active.
Install
yarn add @gdo-bzh/use-toggle-button-group-state react # github package registry
yarn add use-toggle-button-group-state react # npmjs registry
# or
npm install --save @gdo-bzh/use-toggle-button-group-state react # github package registry
npm install --save use-toggle-button-group-state react # npmjs registry
Usage
import React from "react";
import { UseToggleButtonState } from "@gdo-bzh/use-toggle-button-group-state";
const Example = () => {
const { handleSelect, currentSelectedId } = useToggleButtonGroupState({
selectedId: "first",
});
const onButtonClick = (event) => console.log(event.currentTarget.name);
return (
<div>
<button
type="button"
name="first"
className={
currentSelectedId === "first" ? "button button--selected" : "button"
}
onClick={handleSelect(onButtonClick)}
>
First
</button>
<button
type="button"
name="second"
className={
currentSelectedId === "second" ? "button button--selected" : "button"
}
onClick={handleSelect(onButtonClick)}
>
Second
</button>
</div>
);
};
Types
type CallbackFunctionVariadic = (...args: any[]) => void;
type State = {
/**
* default selected button id. If not set, no element is selected by default.
*/
selectedId?: string;
/**
* the key attribute used to uniquely resolve each toggle-button. The default value is 'name'
*/
attributeId?: string;
};
type ClickHandler = (
callback: CallbackFunctionVariadic
) => React.ReactEventHandler<HTMLElement>;
type UseToggleButtonGroupState = (
initialState?: State
) => {
/**
* selection handler. It accepts as single parameter, the specific action attached to the button click event.
*/
handleSelect: ClickHandler;
/**
* current selected button id
*/
currentSelectedId: State["selectedId"];
};
License
MIT © gdo-bzh