Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React-native – Lint error while providing a callback function as a prop to child component (JSX props should not use functions)

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading