score:9

Accepted answer

You can use useImperativeHandle with forwardRef.

From the docs,

useImperativeHandle customizes the instance value that is exposed to parent components when using ref. As always, imperative code using refs should be avoided in most cases. useImperativeHandle should be used with forwardRef

const Child = React.forwardRef((props,ref) => {

    //validate will be available to parent component using ref
    useImperativeHandle(ref, () => ({
      validate() {
        // to validate this component
        console.log("I'm clicked");
      }
    }));

    return (
        <>Some code here</>
    )
})

In the parent compoennt you can access child function as,

function validateChildren() {
   refs.current.forEach(child => {
      child.validate(); // you can access child method here 
   });
}

Demo


Related Query

More Query from same tag