use-controllable-state
Since: ver.7.6.0
Creates a controllable state. E.g: components that have internal state management that could be
overwritten by external props.
Props
| Prop name | Type | Default | Description |
|---|---|---|---|
state | T | undefined | The state value to control the component. If provided, the component will not manage its own state. | |
defaultState | T | undefined | The default state value to use when the component is not controlled. |
When the state is provided, only allows setting the state value from outside of the component.
Otherwise, the hook creates a new state with working setState function.
E.g.: ChoiceWrapper selected state, Tooltip active state and others.
import { Button, ButtonGroup, useControllableState } from '@flixbus/honeycomb-react';
function ControlledButton({ appearance, defaultAppearance, onClick }) {
const [state, setState] = useControllableState({
state: appearance,
defaultState: defaultAppearance,
});
const toggle = () => {
setState((prevState) => prevState === 'primary' ? 'secondary' : 'primary');
if (onClick) {
onClick();
}
};
return <Button appearance={state} onClick={toggle}>{state}</Button>;
}
const [externalState, setExternalState] = React.useState('primary');
const externalToggle = () => setExternalState(externalState === 'primary' ? 'danger' : 'primary');
<>
<ButtonGroup>
<ControlledButton defaultAppearance="primary" />
<ControlledButton appearance="primary" />
<ControlledButton appearance={externalState} onClick={externalToggle} />
</ButtonGroup>
</>