Menu

How to access the DOM element of the Child Component in React?

Shivangi Rajde 10 months ago 0 663

In this tutorial, we’ll provide an overview of refs in React and how to use them.

What are Refs in React?

Refs in React provide a way to access the DOM nodes or React components directly. Refs can be used to modify a component’s behavior or to access the underlying DOM structure for animating or manipulating it. In this tutorial, we’ll provide an overview of refs in React, including an example of using them with functional components.

In React, refs are created using the React.createRef() method. Refs are then attached to React elements using the ref attribute. Let’s have a look at the examples of Ref using both functional components as well as class components.

Here’s an example of creating a ref in a functional component:

import React, { useRef } from 'react';

function MyComponent() {
  const myRef = useRef(null);

  function handleClick() {
    myRef.current.focus();
  }

  return (
    <div>
      <input type="text" ref={myRef} />
      <button onClick={handleClick}>Focus</button>
    </div>
  );
}

In the example above, a ref is created using the useRef hook, and then attached to an input element using the ref attribute. Once attached, the ref can be used to access the underlying DOM node directly in the handleClick function.

Here’s an example of using refs to access a child component in a functional component:

import React, { useRef } from 'react';
import ChildComponent from './ChildComponent';

function ParentComponent() {
  const childRef = useRef(null);

  function handleClick() {
    childRef.current.doSomething();
  }

  return (
    <div>
      <ChildComponent ref={childRef} />
      <button onClick={handleClick}>Do something</button>
    </div>
  );
}

In the example above, a ref is created using the useRef hook and attached to a child component using the ref attribute. The doSomething method of the child component can then be accessed directly using the current property of the ref in the handleClick function.

Here’s an example of creating a ref in a React component using a class component:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }

  render() {
    return (
      <div>
        <input type="text" ref={this.myRef} />
      </div>
    );
  }
}

In the example above, a ref is created using, and then attached to an input element using the ref attribute. Once attached, the ref can be used to access the underlying DOM node directly:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }

  componentDidMount() {
    this.myRef.current.focus();
  }

  render() {
    return (
      <div>
        <input type="text" ref={this.myRef} />
      </div>
    );
  }
}

In the example above, we’re using the componentDidMount() lifecycle method to focus on the input element when the component is mounted. This is accomplished by accessing the underlying DOM node of the input element using the current property of the ref.

Refs provide a way to access the underlying DOM structure of a component directly in React. This can be useful for modifying a component’s behavior or for manipulating the DOM structure directly. With functional components, refs can be created using the useRef hook and attached to elements using the ref attribute.

What is forwardRef() in React?

forwardRef() is a function in React that allows you to pass a ref down to a child component. This can be useful in cases where the parent component needs to access the child component’s DOM node or React component instance directly.

In a typical React component, you can access the child component using the props object. However, if you need to access a child component ref directly, you need to use the forwardRef() function.

Here’s an example of using forwardRef() with a functional component:

import React, { forwardRef } from 'react';

const MyComponent = forwardRef((props, ref) => (
  <div ref={ref}>
    <input type="text" />
  </div>
));

function ParentComponent() {
  const myRef = useRef(null);

  function handleClick() {
    myRef.current.focus();
  }

  return (
    <div>
      <MyComponent ref={myRef} />
      <button onClick={handleClick}>Focus</button>
    </div>
  );
}

In the example above, the MyComponent a functional component is wrapped with the forwardRef() function, which allows the ref to be passed down to the child component. The ref is then attached to the <div> element inside the MyComponent component.

In the ParentComponent, a ref is created using the useRef() hook, and then passed down to the MyComponent component using the ref attribute. Once attached, the ref can be used to access the underlying DOM node directly in the handleClick function.

forwardRef() is a useful function in React that allows you to pass a ref down to a child component. This can be useful in cases where the parent component needs to access the child component’s DOM node or React component instance directly. With forwardRef(), you can easily create more flexible and reusable components in React.

What if we want to access something else from the child component, for example, a simple function to focus the input? Here comes the useImperativeHandle() hook to help us, let’s understand the hook as explained below.

useImperativeHandle() in React

useImperativeHandle() is a hook in React that allows you to expose certain functions or values from a child component to its parent component. This can be useful in cases where the parent component needs to interact with the child component in a specific way.

With useImperativeHandle(), you can define a set of functions or values that are accessible from the parent component using a ref. This can be useful in cases where the parent component needs to trigger certain actions on the child component or access specific properties.

Here’s an example of using useImperativeHandle() with a child component:

import React, { forwardRef, useImperativeHandle } from 'react';

const ChildComponent = forwardRef((props, ref) => {
  const inputRef = useRef(null);

  useImperativeHandle(ref, () => ({
    focusInput: () => {
      inputRef.current.focus();
    },
    value: inputRef.current.value
  }));

  return (
    <div>
      <input type="text" ref={inputRef} />
    </div>
  );
});

function ParentComponent() {
  const childRef = useRef(null);

  function handleClick() {
    childRef.current.focusInput();
  }

  return (
    <div>
      <ChildComponent ref={childRef} />
      <button onClick={handleClick}>Focus input</button>
    </div>
  );
}

In the example above, the ChildComponent a functional component is wrapped with the forwardRef() function, which allows the ref to be passed down to the child component. The useImperativeHandle() hook is used to define a set of functions and values that are accessible from the parent component using the ref.

In this case, the focusInput() the function is defined to focus the input field in the ChildComponent, and the value property is defined to access the current value of the input field.

In the ParentComponent, a ref is created using the useRef() hook, and then passed down to the ChildComponent component using the ref attribute. Once attached, the ref can be used to call the focusInput() function directly in the handleClick function.

useImperativeHandle() is a useful hook in React that allows you to expose certain functions or values from a child component to its parent component. This can be useful in cases where the parent component needs to interact with the child component in a specific way. With, useImperativeHandle() you can easily create more flexible and reusable components in React.

Remember that useImperativeHandle() can be used only inside a component wrapped in forwardRef()

Some of the scenarios of using Refs in React

There are several scenarios in which using refs in React is required:

  1. Managing focus: Refs can be used to manage focus on an element. For example, when a user clicks on a button, you may want to focus on a form input element so they can start typing right away. In this case, you would use a ref to access the input element and call the focus() method.
  2. Accessing DOM elements: Refs can be used to access the underlying DOM elements of a React component. For example, if you want to animate a component when it appears on the screen, you can use a ref to access the DOM node and manipulate it using a JavaScript animation library.
  3. Integrating with third-party libraries: Refs can be used to integrate with third-party libraries that expect a reference to a DOM element. For example, if you’re using a charting library that expects a reference to a canvas element, you can use a ref to provide that reference.
  4. Uncontrolled components: In some cases, you may want to create an uncontrolled component, which is a component that manages its own state without the need for a parent component to manage it. Refs can be used to access the values of uncontrolled components, such as input fields.

It’s worth noting that using refs should be a last resort in React. In most cases, you can manage the state using props and avoid using refs altogether. However, in the scenarios described above, using refs is necessary to achieve the desired functionality.

– Advertisement – BuzzMag Ad
Written By

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *