Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[@mantine/hooks] use-toggle: Add handling for more than two values in…
… an array (#2912) * [@mantine/hooks] use-toggle: Add handling for more than two values in an array * [@mantine/hooks] use-toggle: Fixes after review
- Loading branch information
Showing
2 changed files
with
27 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,21 +1,12 @@ | ||
import { useState } from 'react'; | ||
import { useReducer } from 'react'; | ||
|
||
export function useToggle<T = boolean>(options: readonly [T, T] = [false, true] as any) { | ||
const [state, setState] = useState(options[0]); | ||
export function useToggle<T = boolean>(options: readonly T[] = [false, true] as any) { | ||
const [[option], toggle] = useReducer((state: T[], action: React.SetStateAction<T>) => { | ||
const value = action instanceof Function ? action(state[0]) : action; | ||
const index = Math.abs(state.indexOf(value)); | ||
|
||
const toggle = (value?: React.SetStateAction<T>) => { | ||
if (typeof value !== 'undefined') { | ||
setState(value); | ||
} else { | ||
setState((current) => { | ||
if (current === options[0]) { | ||
return options[1]; | ||
} | ||
return state.slice(index).concat(state.slice(0, index)); | ||
}, options as T[]); | ||
|
||
return options[0]; | ||
}); | ||
} | ||
}; | ||
|
||
return [state, toggle] as const; | ||
return [option, toggle as (value?: React.SetStateAction<T>) => void] as const; | ||
} |