I am trying to implement a n (which will be defined) selection custom hook in order to use for components such as; text inputs, radio buttons etc.
e.g: You have a selection in a form. Let's say gender selection which you would have 3 options; male, female, I don't prefer to say. For this I just wrote something like this.
import {useCallback, useState} from 'react';
export const useTripleSelection = () => {
const [value, setValue] = useState(0);
const toggleZero = useCallback(() => {
setValue(0);
}, []);
const toggleOne = useCallback(() => {
setValue(1);
}, []);
const toggleTwo = useCallback(() => {
setValue(2);
}, []);
return [value, toggleZero, toggleOne, toggleTwo];
};
But the problem is I will need something further for future development, I don't want to be have to write double, triple, quadra selection hook.
Is there a way to implement a N selection hook according to this relation ? Can you help me out ? Thanks.
I'm not sure that what you are trying to achieve is a best practice. You'd probably be better off with a state with an enum, like:
export enum TGenderValues {
male = 'male',
female = 'female',
notSelected = 'not_selected',
}
Anyway, you could achieve what you want with
import { useCallback, useState } from 'react';
export const useGetNthSelection = () => {
const [value, setValue] = useState<number>(0);
const togglerForNthSelection = useCallback((selectionNumber: number) => {
return () => {
setValue(selectionNumber);
};
}, []);
return [value, togglerForNthSelection];
};
const YourComponent = () => {
const [value, togglerForNthSelection] = useGetNthSelection();
return (
<YourInput
onSelectA={togglerForNthSelection(1)}
onSelectK={togglerForNthSelection(10)}
/>
);
}