What is the right way to call child component functions in React using React.forwardRef()?

Asked
Active3 hr before
Viewed126 times

9 Answers

functionsusingchildcomponentreact
90%

When the ref is attached, ref.current will point to the <button> DOM node.,The second ref argument only exists when you define a component with React.forwardRef call. Regular function or class components don’t receive the ref argument, and ref is not available in props either.,This means that refs intended for our FancyButton component will actually be attached to the LogProps component:

function FancyButton(props) {
  return (
    <button className="FancyButton">
      {props.children}
    </button>
  );
}
load more v
88%

Ref forwarding is not limited to DOM components. You can forward refs to class component instances, too,The second ref argument in the InputRef component only exists when you define a component with React.forwardRef call,Regular function or class components don’t receive the ref argument, and ref is not available in props either

Pretag
 Pretag team - issue, fix, solve, resolve
72%

https://facebook.github.io/react/tips/expose-component-functions.html for more answers ref here Call methods on React children components,For functional components easiest way is,you can use ref to call the function of the child component from the parent

const { forwardRef, useRef, useImperativeHandle } = React;

// We need to wrap component in `forwardRef` in order to gain
// access to the ref object that is assigned using the `ref` prop.
// This ref is passed as the second parameter to the function component.
const Child = forwardRef((props, ref) => {

  // The component instance will be extended
  // with whatever you return from the callback passed
  // as the second argument
  useImperativeHandle(ref, () => ({

    getAlert() {
      alert("getAlert from Child");
    }

  }));

  return <h1>Hi</h1>;
});

const Parent = () => {
  // In order to gain access to the child component instance,
  // you need to assign it to a `ref`, so we call `useRef()` to get one
  const childRef = useRef();

  return (
    <div>
      <Child ref={childRef} />
      <button onClick={() => childRef.current.getAlert()}>Click</button>
    </div>
  );
};

ReactDOM.render(
  <Parent />,
  document.getElementById('root')
);
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>

<div id="root"></div>
load more v
65%

So let us create a parent component first So we have created a component with a button to call the child function later on.,For calling Child Component function from parent component in hooks we are using React.forwardRef and React.useImperativeHandle hooks from React. Now let us know briefly about these two. What are they? How are they used? And the most important question, how are we going to use them? So let’s get started!,Child component is rendered and a ref is created using React.useRef named childRef. The button we created in parent component is now used to call the child component function childRef.current.showAlert();

Arguments and return type: React calls this function with two arguments one is props and the other is ref. This returns a react node something like this.

const someComponent = React.forwardRef((props,ref)=>(    <div ref={ref} className="title">        {props.title}    </div>))
load more v
75%

React.forwardRef takes a function with props and ref arguments. This function returns a JSX Element.,The Button will be a function component. The forwardRef will pass its props and ref attributes to the props and ref args respectively.,Counter has child components, button and div. We can set the ref attribute on Counter on either of these. We do that using the React.forwardRef API.

Ref is a mutable reference to an Object. This can be a DOM instance or a class instance. It is greatest using either the useRef of the createRef APIs. The refs are then assigned to the ref property of a JSX element.

const aRef = React.createRef()// Here, aRef will hold the HTMLButtonElement instance of the button in the `current` property.<button ref={aRef}>Click</button>// aRef will hold the object of the class Counter in its `current` property.<Counter ref={aRef} />

Now, Counter is a React component, unlike button which is an HTML element. aRef will hold the object of the class Counter, but we can make the ref pass down to the child components of the Counter component so the aRef will hold the instance of its child component instead of Counter itself. That is what we call ref forwarding.

class Counter extends React.Component {    constructor() {        this.state = {            count: 0        }    }    render() {        return (            <div>                Count: {this.state.count}                <button onClick={() => this.setState({count: this.state.count + 1})}>Incr</button>            </div>        )    }}
load more v
40%

Pretag
 Pretag team - issue, fix, solve, resolve
22%

@artem-malko As I understand, in <Wrapper ref=...>, ref refers to wrapper component itself. I.e. React processes it and removes from props. If it's desirable to reference wrapped (child) component instead, it's possible to link wrapper's ref to child using forwardRef.,@dheeraj-br ref won't appear in child component's props when the component is not wrapped in React.forwardRef. It's a special case like key, not a normal property.,This code means that var emailRef = React.createRef(); may ref input dom, because React.forwardRef pass it along the children elements.

I have this setup in react-native.
But since the last release(or 2), it has broken for me.
From parent, customRef.current now only contains

"_nativeTag": 145,
"_children": [],
"viewConfig": {
   ...
}
load more v
60%

By exporting the component with forwardRef, the Function now has two arguments, props and ref, where the latter needs to be used in useImperativeHandle hook.,Also, you have to export the component with forwardRef HOC function.,The Class version is pretty straighforward, the method setFromOutside is public, thus, it's visible from the parent by means of the child reference.

import CChild from './CChild'
import FChild from './FChild'

function Mock (props) {
  const fref = useRef()
  const cref = useRef()

  const handleClick = e => {
    fref.current.setFromOutside('HELLO from Parent')
    cref.current.setFromOutside('HELLO from Parent')
  }
  return (
    <div>
      <button onClick={handleClick}>Show Me!</button>
      <FChild ref={fref} />
      <CChild ref={cref} />
    </div>
  )
}
load more v
48%

React components represent DOM tags that make up a particular part of a UI returned by the render method. For cases where you want to interact with the DOM node outside the regular React lifecycle, we can use refs.,Revisiting our top-level parent component, we pass our reference array an index value as we map over our data.,Alternatively, according to the docs, we can “forward” the ref directly to a child component using forwardRef. We can use the regular ref attribute and get the reference to one of the children from the component wrapped inforwardRef as regular props.

Let’s declare a parent-child relationship where a list component renders some undetermined number of rows:

// Parent: Feed// Child: FancyRow function Feed({ edges }: FeedProps): React.Element<'div'> {  const parentRef = useRef<HTMLDivElement>();  return (    <div className={styles[‘feed’]}>      <h4 className={styles[‘feed__item-title’]}>         List Container      </h4>      {edges.map((edge, i) => (      <FancyRow key={i} />      ))}    </div>  );}
load more v

Other "functions-using" queries related to "What is the right way to call child component functions in React using React.forwardRef()?"