This has a simple work around, but I am a student and trying to learn typescript. Thank you for the help.
I am trying to convert some custom hooks to typescript
import { useState } from 'react';
export default function useToggle(defaultValue: Boolean = false) {
const [value, setValue] = useState(defaultValue);
const toggleValue = (value?: boolean) => {
setValue((currentValue) =>
typeof value === 'boolean' ? value : !currentValue
);
};
return [value, toggleValue] as const;
}
The type of ToggleValue is Boolean | undefined. I would like to use it as a onClick and just send the function for the default toggle. This works when not using typescript. I think it is because onClick can accept undefined but cannot accept the optional Boolean.
<button onClick={toggleValue}>toggle</button> {/* MAKE ThIS WORK? */}
<button onClick={() => toggleValue(true)}>set True</button>
<button onClick={() => toggleValue(false)}>set False</button>
Using Typescript I am required to write it as a callback even when not providing parameters
<button onClick={()=>toggleValue()}>toggle</button>
When you pass a function to the onClick event it will always pass the mouse event as the first argument and typescript knows it and is warning you that this event is missing when you use it as such.
You have two solutions to handle this issue, the first is the one your proposed:
<button onClick={()=>toggleValue()}>toggle</button>
When no argument is passed to toggleValue.
Otherwise you can add the click event to your toggleValue function:
const toggleValue = (e: React.MouseEvent<HTMLButtonElement>, value?: boolean) => {
But when you need the value argument to your toggleValue you'll also have to pass the event as such:
<button onClick={(e) => toggleValue(e, true)}>set True</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With