I have a component which includes another component (from headlessui/react) defined as follows:
export default function MyComponent(props) {
const [selectedState, setState] = useState('');
return (
<div>
<RadioGroup value={selectedState} onChange={setState}>
...
</RadioGroup>
</div>
)
}
In the onChange I would like to first call a function which does something and then calls setState. However, nomatter what I try, I can’t get this to work.
I’ve tried:
onChange={() => {
doSomethingFirst();
return setState;
}
onChange={() => {
doSomethingFirst();
// This requires an argument and I'm not sure what the argument should be
setState();
}
// Even this fails
onChange={() => setState;}
What do I do to get this working?
>Solution :
When you pass onChange directly to RadioGroup it will invoke your setState with any arguments the RadioGroup supplies. Because setState only takes one argument that’s thereby equal to doing onChange={arg => setState(arg)} which already shows how to accomplish what you’re trying to do. Just emulate this exact behaviour and add in your function call:
onChange={arg => {
doSomethingHere()
return setState(arg)
}}