I've a parent-child functional component structure, where parent fetches data to be displayed and child component displays the data. I am updating parent's state from child component. I'm sending a handler function from parent to the child as a prop, which is invoking the parent's handler function. Inside the parent's handler function, I'm updating state, however, ESLint is throwing error (JSX props should not use functions). Here is what I've done so far:
Parent Component:
const [startTime, setStartTime] = useState(new Date());
const myHandler = () => {
const tn = new Date();
setStartTime(tn);
}
return (
<ChildComponent myHandler={myHandler} />
);
Child Component:
interface Props {
myHandler:(params: any) => any;
}
const someAction = useCallback(
(studentId: Student['id']) => () => {
navigation.push(STUDENTROUTE, { studentId });
myHandler(studentId);
},
[navigation]
);
Issue is happening on the parent component where I'm passing the handler function as a prop to the child component. Error I'm getting in couple of components is:
114:7 error JSX props should not use functions react/jsx-no-bind
What can I do to correct this error?
CodePudding user response:
Your parent component is creating myHandler
every time it runs, which the linter rule says should be avoided. Create it only once, when the component first mounts, so that it passes down a static reference every time.
const myHandler = useCallback(() => {
const tn = new Date();
setStartTime(tn);
}, [setStartTime]);