'How to fix the error jsx no new function as prop with typescript and react?
i want to fix the eslinting rule error jsx no new function as prop using typescript and react.
i have code like below,
const Parent = () => {
const handleChange = useCallback((value: boolean) => {
setField(value);
}, [setField]);
return (
<RadioButton label="first" onChange={() => handleChange(true)}/> //error here
<RadioButton label="second" onChange={() => handleChange(false)}/> //error here
);
}
i understand that using onChange={() => handleChange(true)} is an anti pattern and hence the error . but i have tried
onChange={handleChange(true)} this causes maximum state update depth reached error.
how can i fix this such that i dont see the jsx no new function as prop error. could someone help me with this. thanks.
Solution 1:[1]
Just pass the callback as the prop:
<RadioButton label="first" onChange={handleChange}/>
Not 100% sure about your use case, but I'd recommend not using useCallback:
const handleChange = (value: boolean) => {
setField(value);
};
Also make sure that the RadioButton's onChange prop has the signature (value: boolean) => void and not using some sort of React.ChangeEvent. If it uses React.ChangeEvent, you will have to adjust the signature of handleChange.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | twharmon |
