ideas
ideas copied to clipboard
useInputFocus
Hook which returns whether the input is focused or not. works great when used with useInputValue.
import useInputValue from '@rehooks/input-value';
import useInputFocus from '@rehooks/input-focus';
function MyComponent() {
let name = useInputValue('Jamie');
let {isFocused, bind} = useInputFocus()
// bind = { onFocus: [function], onBlur: [function] }
// name = { value: 'Jamie', onChange: [Function] }
return <input {...name} {...bind}/>;
}
Could just be useElementFocus()
Can I claim this?
What should its name be element-focus
or just focus
, what do you think?
done at: https://github.com/pierreneter-repositories/element-focus
How about just useFocus
?
@j-f1 that sounds more natural.
ok, so, i will rename that to focus
and useFocus
right?
@pierrenetter why not use array destructuring?
const [hasFocus, bind] = useFocus()
what do you think @jamiebuilds
ping! noone here :( 😞
/**
* Hook that returns a boolean `hasFocus` value and a set of even handler props
* (`onFocus`, `onBlur`) to pass to the target element.
* @param {any} [defaultValue] The default value. (`false`)
* @example
* // Basic usage
* const [hasFocus, focusProps] = useFocus();
* React.useEffect(() => {
* if (hasFocus) {
* setOtherValue("");
* }
* }, [hasFocus, setOtherValue]);
* // Rendering:
* return (<>
* <input type="text" name="myValue" {...focusProps} />
* <input type="text" name="otherValue" value={otherValue} />
* </>);
* @example
* // Advanced usage
* const [hasFocus, focusProps, setHasFocus] = useFocus();
* // ... Same as Basic usage, but you can use setHasFocus to change state...
*/
export function useFocus(defaultValue = false) {
const [hasFocus, setHasFocus] = React.useState(defaultValue);
const hasFocusProps = {
onFocus: React.useCallback(
/** @param {React.SyntheticEvent<HTMLElement>} e */
function onFocus(e) {
setHasFocus(true);
},
[],
),
onBlur: React.useCallback(
/** @param {React.SyntheticEvent<HTMLElement>} e */
function onBlur(e) {
setHasFocus(false);
},
[],
),
};
return [hasFocus, hasFocusProps, setHasFocus];
}
Array destructuring should be used IMO, so that you don't have to constantly rename the returned values in the very common situation where you're using 2 or more of the same type of hook.