@engie-group/fluid-design-system-react
Version:
Fluid Design System React
45 lines (37 loc) • 1.19 kB
text/typescript
import React, { useEffect } from 'react';
/**
* Apply the inert attribute to an HTMLElement depending on the value of the inert parameter.
* @param ref The reference to the HTMLElement to which the inert attribute will be applied.
* @param inert Whether the inert attribute should be applied or not.
*/
export const useInert = (ref: React.RefObject<HTMLElement | null>, inert = false) => {
useEffect(() => {
if (!ref.current) {
return;
}
const element = ref.current;
element.inert = inert;
return () => {
element.inert = false;
};
}, [inert, ref]);
};
export const useStateControl = <T>(
initialValue: T,
controlledValue: T,
changeCallback?: (value: T) => void
) => {
const [uncontrolledValue, setUncontrolledValue] = React.useState(initialValue);
const setValue = React.useCallback(
(value: T, emit: boolean = true) => {
if (emit) {
changeCallback?.(value);
}
if (controlledValue === undefined) {
setUncontrolledValue(value);
}
},
[controlledValue, changeCallback]
);
return [controlledValue === undefined ? uncontrolledValue : controlledValue, setValue] as const;
};