Is it possible to add ref to the props.children elements?

Viewed 8343

I have a Form and Input components, which are rendered as below.

<Form>
   <Field />
   <Field />
   <Field />
</Form>

Form component will act as wrapper component here and Field component ref are not being set here. I want iterate through props.children in Form Component and want to assign a ref attribute to each children. Is there any possibility to achieve this?

2 Answers

You need Form to inject your refs with React.Children and React.cloneElement APIs:

const FunctionComponentForward = React.forwardRef((props, ref) => (
  <div ref={ref}>Function Component Forward</div>
));

const Form = ({ children }) => {
  const childrenRef = useRef([]);

  useEffect(() => {
    console.log("Form Children", childrenRef.current);
  }, []);

  return (
    <>
      {React.Children.map(children, (child, index) =>
        React.cloneElement(child, {
          ref: (ref) => (childrenRef.current[index] = ref)
        })
      )}
    </>
  );
};

const App = () => {
  return (
    <Form>
      <div>Hello</div>
      <FunctionComponentForward />
    </Form>
  );
};

Edit Vanilla-React-Template (forked)

You can map children create new instance of component based on it using one of two ways showed in React Docs.

  • With React.Children.map and React.cloneElement (this way, key and ref from original element are preserved)

  • Or only with React.Children.map (Only ref from original component is preserved)

function useRefs() {
  const refs = useRef({});

  const register = useCallback((refName) => ref => {
    refs.current[refName] = ref;
  }, []);

  return [refs, register];
}

function WithoutCloneComponent({children, ...props}) {

 const [refs, register] = useRefs(); 

 return (
    <Parent>
     {React.Children.map((Child, index) => (
       <Child.type 
         {...Child.props}
         ref={register(`${field-${index}}`)}
         />
    )}
    </Parent>
 )
}

function WithCloneComponent({children, ...props}) {

 const [refs, register] = useRefs(); 

 return (
    <Parent>
     {
       React.Children.map((child, index) => React.cloneElement(
         child, 
         { ...child.props, ref: register(`field-${index}`) }
       )
    }
    </Parent>
 )
}
Related