Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access refs of a child component in the parent component

Tags:

reactjs

If I have something like

<Parent>   <Child1 />   <Child2 />   <Child3 /> </Parent> 

And I want to access from Child2 where I have refs="child2refs", how can I do that?

like image 607
user1354934 Avatar asked Jun 05 '16 21:06

user1354934


People also ask

How do you pass ref from child to parent component?

As per DOC: You may not use the ref attribute on functional components because they don't have instances. You should convert the component to a class if you need a ref to it, just like you do when you need lifecycle methods or state. So i think, if you want to use the ref , you need to use class .

How do you find the value of a child component in the parent component?

We can get child component values in the parent component by creating a reference to the child component using the @ref directive in the Parent component. Using the reference instance, you can access the child component values in the parent.

How do you pass ref from child to parent React hooks?

The forwardRef hooks allows React users to pass refs to child components. The ref can be created and referenced with useRef or createRef and then passed in a parent component. Using forwardRef instead of useRef is useful when a ref needs to be accessed in a parent component.


1 Answers

Recommended for React versions prior to 16.3

If it cannot be avoided the suggested pattern extracted from the React docs would be:

import React, { Component } from 'react';  const Child = ({ setRef }) => <input type="text" ref={setRef} />;  class Parent extends Component {     constructor(props) {         super(props);         this.setRef = this.setRef.bind(this);     }      componentDidMount() {         // Calling a function on the Child DOM element         this.childRef.focus();     }      setRef(input) {         this.childRef = input;     }      render() {         return <Child setRef={this.setRef} />     } } 

The Parent forwards a function as prop bound to Parent's this. When React calls the Child's ref prop setRef it will assign the Child's ref to the Parent's childRef property.

Recommended for React >= 16.3

Ref forwarding is an opt-in feature that lets some components take a ref they receive, and pass it further down (in other words, “forward” it) to a child.

We create Components that forward their ref with React.forwardRef. The returned Component ref prop must be of the same type as the return type of React.createRef. Whenever React mounts the DOM node then property current of the ref created with React.createRef will point to the underlying DOM node.

import React from "react";  const LibraryButton = React.forwardRef((props, ref) => (   <button ref={ref} {...props}>     FancyButton   </button> ));  class AutoFocus extends React.Component {   constructor(props) {     super(props);     this.childRef = React.createRef();     this.onClick = this.onClick.bind(this);   }    componentDidMount() {     this.childRef.current.focus();   }    onClick() {     console.log("fancy!");   }    render() {     return <LibraryButton onClick={this.onClick} ref={this.childRef} />;   } } 

Forwarding refs HOC example

Created Components are forwarding their ref to a child node.

function logProps(Component) {   class LogProps extends React.Component {     componentDidUpdate(prevProps) {       console.log('old props:', prevProps);       console.log('new props:', this.props);     }      render() {       const {forwardedRef, ...rest} = this.props;        // Assign the custom prop "forwardedRef" as a ref       return <Component ref={forwardedRef} {...rest} />;     }   }    // Note the second param "ref" provided by React.forwardRef.   // We can pass it along to LogProps as a regular prop, e.g. "forwardedRef"   // And it can then be attached to the Component.   return React.forwardRef((props, ref) => {     return <LogProps {...props} forwardedRef={ref} />;   }); } 

See Forwarding Refs in React docs.

like image 101
arpl Avatar answered Sep 21 '22 17:09

arpl