Could anyone advise me on the best way to convert this hook to a type safe version using Typescript please. Its a simple toggle to display a different 'thing' on toggle state.
useToggle.js
const useToggleButton = ({on,off}) => {
const [toggle, setToggle] = React.useState(false)
const ToggleButton = () => (
<div
role="button"
onClick={() => setToggle(!toggle)}
data-testid="portal-toggle-btn"
>
{toggle? on : off}
</div>
)
return [ToggleButton, toggle, setToggle]
}
The thing is that it returns an array with the component, state and setState function. My attempt is below but I get the errors
TS2605: JSX element type 'IReturnType' is not a constructor function for JSX elements. Type 'IReturnType' is missing the
following properties from type 'Element': type, props, key
TS2739: Type '(boolean | Dispatch<SetStateAction<boolean>>)[]' is
missing the following properties from type 'IReturnType': component,
state, func
useToggle.tsx
import * as React from 'react'
interface IToggleBntProps {
on: any
off: any
}
interface IState {
bol: boolean
}
interface IReturnType {
component: React.FunctionComponent
state: boolean
func: (bol: boolean) => IState
}
const useToggleButton = ({ on, off }: IToggleBntProps): IReturnType => {
const [toggle, setToggle] = React.useState(false)
const ToggleButton = () => (
<div
role="button"
onClick={() => setToggle(!toggle)}
data-testid="portal-toggle-btn"
>
{toggle ? on : off}
</div>
)
return [ToggleButton, toggle, setToggle]
}
export default useToggleButton