惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

人人都是产品经理
人人都是产品经理
D
Docker
GbyAI
GbyAI
B
Blog RSS Feed
博客园 - 司徒正美
博客园 - Franky
美团技术团队
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
aimingoo的专栏
aimingoo的专栏
C
Check Point Blog
IT之家
IT之家
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
www.infosecurity-magazine.com
www.infosecurity-magazine.com
AI
AI
O
OpenAI News
Attack and Defense Labs
Attack and Defense Labs
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
T
Tailwind CSS Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
S
Secure Thoughts
博客园 - 聂微东
L
LINUX DO - 最新话题
U
Unit 42
SecWiki News
SecWiki News
A
Arctic Wolf
Schneier on Security
Schneier on Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
V
Visual Studio Blog
量子位
The Cloudflare Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
大猫的无限游戏
大猫的无限游戏
Google DeepMind News
Google DeepMind News
G
Google Developers Blog
T
Threat Research - Cisco Blogs
TaoSecurity Blog
TaoSecurity Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
B
Blog
博客园 - 【当耐特】
C
CERT Recently Published Vulnerability Notes
Scott Helme
Scott Helme
Last Week in AI
Last Week in AI
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Microsoft Security Blog
Microsoft Security Blog
Apple Machine Learning Research
Apple Machine Learning Research
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
A
About on SuperTechFans
博客园 - 三生石上(FineUI控件)
Latest news
Latest news

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
React forwardRef(): How to Pass Refs to Child Components
Dmitri Pavlutin · 2023-04-06 · via Dmitri Pavlutin Blog

To access a DOM element rendered in the component's body you can use a ref created by useRef() hook.

But what if you need to access a DOM element of a child component? Then a simple ref is not enough and you have to combine refs with React.forwardRef(): a technique called refs forwarding.

Also, useImperativeHandle() is a hook that extends the capabilities of forwardRef() by giving the parent component access to more goodies like imperative methods of a child component.

Let's see how it works.

Table of Contents

  • 1. Refs in child components
  • 2. forwardRef()
  • 3. useImperativeHandle()
  • 4. Deep refs forwarding
  • 5. Pitfalls
    • 5.1 ref is undefined or null
    • 5.2 Pass ref using a prop
    • 5.3 Anonymous component
  • 6. forwardRef() in TypeScript
  • 7. Conclusion

1. Refs in child components

There are situations when you have to work with the DOM because the existing React abstractions (components, state, props, hooks, context) do not cover all possible use cases:

  • call methods on DOM elements to manage focus, scroll, and text selection
  • integrate 3rd party scripts that are unaware of React abstractions
  • working with animation libraries, for example GSAP

Let's recall how to access a DOM element directly from the body of the component:


import { useRef, useEffect } from 'react'

export function Parent() {

const elementRef = useRef() // create the ref

useEffect(() => {

// after mounting

console.log(elementRef.current) // logs <div>Hello, World!</div>

}, [])

return <div ref={elementRef}>Hello, World!</div> // assign the ref

}


Open the demo.

const elementRef = useRef() creates a ref. Then elementRef is assigned to the ref attribute of the tag: <div ref="elementRef">.

elementRef after mounting will contain the DOM element instance (useEffect() hook with an empty array as deps detects when the component mounts).

Open the demo and you'll see the element logged to the console.

Ok, so what is the limitation of this approach? A problem arises when the element is not rendered directly in the body of the component, but rather in a child component.

Let's modify the previous example by extracting the <div>Hello, World!</div> into a child component <Child>. Also, let's create a prop ref on <Child>, to which <Parent> assigns elementRef:


import { useRef, useEffect } from 'react'

export function Parent() {

const elementRef = useRef()

useEffect(() => {

// Does not work!

console.log(elementRef.current) // logs undefined

}, [])

return <Child ref={elementRef} /> // assign the ref

}

function Child({ ref }) { // a new component

return <div ref={ref}>Hello, World!</div>

}


Open the demo.

Is this code working? Open the demo and you'll see that after mounting elementRef.current contains undefined.

<Parent> couldn't access the DOM element from the child component.

React ref as prop does not work

React also throws a useful warning: Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

Let's follow React's advice and see how forwardRef() can help.

2. forwardRef()

Now is the right moment to introduce forwardRef().

forwardRef() is a higher-order component that wraps a React component. The wrapped component works the same way as the original component but also receives as the second parameter a ref: the forwarded ref from the parent component.

React forwardRef()

Let's wrap the child component into forwardRef() with the goal to connect parent's elementRef with child's <div>Hello, World!</div>:


import { useRef, useEffect, forwardRef } from 'react'

export function Parent() {

const elementRef = useRef()

useEffect(() => {

// Works!

console.log(elementRef.current) // logs <div>Hello, World!</div>

}, [])

return <Child ref={elementRef} /> // assign the ref

}

const Child = forwardRef(function(props, ref) {

return <div ref={ref}>Hello, World!</div>

})


Open the demo.

The parent component assigns elementRef to the child component <Child ref={elementRef} />. Then, thanks to being wrapped into forwardRef(), the child component gets the ref from the second parameter and uses it on its element <div ref={ref}>.

After mounting elementRef.current in the parent component contains the DOM element from child component. Open the demo: it works!

That's the purpose of forwardRef(): give the parent component access to DOM elements in the child component.

3. useImperativeHandle()

What if you want to access something else from the child component? For example, a simple function to focus the input.

That's where useImperativeHandle() hook can help you.


import { forwardRef, useImperativeHandle } from 'react'

const MyComponent = forwardRef(function(props, ref) {

useImperativeHandle(ref, function getRefValue() {

return {

// new ref value...

method1() { },

method2() { }

}

}, []) // dependencies

return <div>...</div>

}


useImperativeHandle(ref, getRefValue, deps) is built-in React hook that accepts 3 arguments: the forwarded ref, the function that returns the new ref value, and the dependencies array.

The value returned of getRefValue() function becomes the value of the forwarded ref. That's the main benefit of useImperativeHandle(): you can customize the forwarded ref value with whatever you want.

React forwardRef() and useImperactiveHandle()

For example, let's use the hook and give the parent an object with methods focus() and blur():


import { useRef, forwardRef, useImperativeHandle } from 'react'

export function Main() {

const methodsRef = useRef()

const focus = () => methodsRef.current.focus()

const blur = () => methodsRef.current.blur()

return (

<>

<FocusableInput ref={methodsRef} />

<button onClick={focus}>Focus input</button>

<button onClick={blur}>Blur input</button>

</>

)

}

const FocusableInput = forwardRef(function (props, ref) {

const inputRef = useRef()

useImperativeHandle(ref, // forwarded ref

function () {

return {

focus() { inputRef.current.focus() },

blur() { inputRef.current.blur() }

} // the forwarded ref value

}, [])

return <input type="text" ref={inputRef} />

})


Open the demo.

useImperativeHandle(ref, ..., []) gives the parent an object with focus() and blur() methods.

Finally, remember that useImperativeHandle() can be used only inside a component wrapped in forwardRef().

4. Deep refs forwarding

You can forward refs more than 1 level down in the component hierarchy. Just wrap each child, grandchild, and so on components in forwardRef(), and pass the ref down until you reach the target DOM element.

Let's forward elementRef 2 times to access the DOM element from a grandchild component:


import { forwardRef, useRef, useEffect } from "react";

export function Parent() {

const elementRef = useRef()

useEffect(() => {

console.log(elementRef.current); // logs <div>Deep!</div>

}, [])

return <Child ref={elementRef} />

}

const Child = forwardRef(function (props, ref) {

return <GrandChild ref={ref} />

})

const GrandChild = forwardRef(function (props, ref) {

return <div ref={ref}>Deep!</div>

})


Open the demo.

elementRef is forwarded to the child component, which then forwards the same ref to the grandchild, which finally connects the ref to <div ref={ref}>Deep!</div>.

Using 2 forwards the parent component elementRef gets access to <div ref={ref}>Deep!</div> in the grandchild.

React deep forwardRef()

As a side note, try to keep the forwarding to a minimum to avoid increasing the code complexity.

5. Pitfalls

5.1 ref is undefined or null

If the forwarded ref is unexpectedly undefined or null, there are usually 2 reasons.

First, you may have forgotten to assign the forwarded ref to ref attribute of the HTML tag:


import { useRef, useEffect, forwardRef } from 'react'

export function Parent() {

const elementRef = useRef()

useEffect(() => {

console.log(elementRef.current) // logs undefined

}, [])

return <Child ref={elementRef} />

}

const Child = forwardRef(function(props, ref) {

return <div>Hello, World!</div> // ref not assigned to ref attribute!

})


Open the demo.

elementRef in the example above is undefined because the forwarded ref isn't assigned to ref attribute of <div>Hello, World!</div> inside the child component.

To fix the problem just assign correctly the ref: <div ref={ref}>Hello, World!</div>.

Second, you may have conditionally displayed the referenced DOM element:


import { useRef, useEffect, forwardRef, useState } from 'react'

export function Parent() {

const elementRef = useRef()

const [show, setShow] = useState(true)

const toggle = () => setShow(!show)

useEffect(() => {

// logs <div>Hello, World!</div> or null

console.log(elementRef.current)

}, [show])

return (

<>

<button onClick={toggle}>Toggle</button>

<Child ref={elementRef} show={show} />

</>

)

}

const Child = forwardRef(function({ show }, ref) {

// displayed conditionally

return show ? <div ref={ref}>Hello, World!</div> : null

})


Open the demo.

The child component renders <div ref={ref}>Hello, World!</div> under a condition. Initially show prop is true, thus elementRef is <div>Hello, World!</div>.

Clicking "Toggle" button makes show become false. This makes the ternary operator in <Child> render null — and not render the div element. Thus elementRef in the parent becomes null.

5.2 Pass ref using a prop

In the first section I mentioned that if you assign to ref prop an actual ref, React will throw a warning Warning: Function components cannot be given refs.

But what about using a custom prop, for example, elementRef, and passing the ref down to the child component using the custom prop?

Let's take a look:


import { useRef, useEffect } from "react"

export function Parent() {

const elementRef = useRef()

useEffect(() => {

// Works!

console.log(elementRef.current); // logs <div>Hello, World!</div>

}, [])

return <Child elementRef={elementRef} />

}

function Child({ elementRef }) {

return <div ref={elementRef}>Hello, World!</div>

}


Open the demo.

The parent component passes elementRef to <Child elementRef={elementRef}> using a custom prop elementRef. The child component then assigns elementRef prop to the tag: <div ref={elementRef}>Hello, World!</div>.

What's your bet, does elementRef in the parent component access the DOM element of the child?

Indeed, it does!

Then the big question is... why bother with using forwardRef()? You can just pass the ref using a prop!

I don't recommend doing so, and here are 2 reasons.

First, using ref attribute (instead of a custom prop like elementRef) is better because it keeps the ref API consistent between class-based, function-based, and HTML tags.

Second, props are immutable in React. Passing the ref using a prop violates the props immutability because the ref eventually is assigned (aka mutated) with the DOM element.

Do you know other issues when passing ref using a custom prop? Write a comment below!

5.3 Anonymous component

An anonymous function doesn't have a name near function keyword.


import { forwardRef } from 'react'

const MyComponent = forwardRef(function() { // Anonymous function

// ...

})


In React dev tools an anonymous function wrapped in forwardRef() results in a component with an unmeaningful name:

Anonymous React component because of forwardRef()

Having no component name in the hierarchy makes it hard to understand what is rendered on the page. In addition, you cannot use the search functionality of the React dev tools to find your component.

To give a component a name use the named function expressions for components wrapped in forwardRef():


import { forwardRef } from 'react'

const MyComponent = forwardRef(function MyComponent() {// Named function

// ...

})


Using function MyComponent() {...} displays the component name in React dev tools:

Named React component in forwardRef()

With the proper names of components, debugging the application is much easier.

6. forwardRef() in TypeScript

React forwardRef() in TypeScript is a bit trickier because you need to specify the type arguments of useRef<T>() in the parent component and forwardRef()<T, P> wrapping the child component. Both functions are generic function types.

forwardRef<V, P>() accepts 2 argument types:

  1. V is the type of the value stored in a ref, which is usually an HTMLDivElement or HTMLInputElement
  2. P is the props type of the wrapped component

useRef<V>() hook in TypeScript has one argument type V: denoting the value type stored in the ref. If you store DOM elements in the ref, V can be HTMLDivElement or HTMLInputElement.

Now let's annotate the parent and child components:


import { useRef, forwardRef } from "react"

export function Parent() {

const elementRef = useRef<HTMLDivElement>(null)

return <Child ref={elementRef} />

}

const Child = forwardRef<HTMLDivElement>(function (props, ref) {

return <div ref={ref}>Hello, World!</div>

})


Open the demo.

useRef<HTMLDivElement>(null) creates a ref that holds a div element because HTMLDivElement is used as the type argument.

The ref is initialised with null — this is important. Otherwise, TypeScript throws a type error when assigning the ref to the child component: <Child ref={elementRef} />.

Finally, when wrapping the child component forwardRef<HTMLDivElement>(...) specify HTMLDivElement as the value type of the forwarded ref.

7. Conclusion

Before ending the post, I advise you to keep the use refs to a minimum.

React is the library which goal is to abstract you from DOM manipulation, cross-browser compatibility, and DOM manipulation performance. React gives you wonderful components, props, state, hooks, and context abstractions to free you from dealing with DOM and browser-specific details.

If you choose to use refs to access DOM, including with the help of forwardRef() and useImperativeHandle(), you are not using React abstractions, you are using the DOM-specific details directly. Code that uses a lot of refs with DOM elements will be harder to maintain in the long run.

Consider using a React abstraction to achieve your goal before using a ref to access DOM. Of course, this isn't always possible, and you have to get your hands dirty from time to time.

Ok.

In conclusion, accessing a DOM element instance is relatively easy when the element is rendered directly in the body of the component. Just assign the ref to the tag: <div ref={elementRef} />.

Things get trickier when the element is rendered inside of a child component. In this case, you have to wrap the child component into the built-in React function forwardRef():


import { forwardRef } from 'react'

function Parent() {

const elementRef = useRef()

return <Child ref={elementRef} />

}

const Child = forwardRef(function(props, ref) {

return <div ref={ref}>...</div>

})


The parent component safely assigns elementRef to the child component <Child ref={elementRef} />. After mounting, elementRef contains the DOM element instance of the child component.

Do you think React should support refs forwarding natively, without the use of forwardRef()?