開源日報每天推薦一個 GitHub 優質開源項目和一篇精選英文科技或編程文章原文,堅持閱讀《開源日報》,保持每日學習的好習慣。

2024年1月28日,開源日報第1087期:
今日推薦開源項目:《Sortable》
今日推薦英文原文:《 Do you really need React.forwardRef ?》


開源項目

今日推薦開源項目:《Sortable》傳送門:項目鏈接

推薦理由: 現代瀏覽器和觸摸設備上可重新排序的拖放列表,不需要jQuery或框架

網站直達:sortablejs.github.io/Sortable/


英文原文

今日推薦英文原文: Do you really need React.forwardRef ?

推薦理由:React.forwardRef 是 React 中的一個函數,解決了在自定義 React 組件中轉發 ref 對象的問題,forwardRef 函數允許覆蓋保留的 ref prop,從而使用標準 prop 名稱進行 ref 轉發


Do you really need React.forwardRef ?

Disclaimer:\ All the information below given are based on my experience and knowledge, it may have some mistakes and I』m not liable for any loss due to that. Please let me know if you have found out any mistakes in the comment section.

Introduction

I hope every reader knows at-least the basics of React js. Before going to the concept, let』s see what is Ref in a nutshell.

  • In React, ref is an object facilitating direct interaction with DOM elements or React components.
  • Essential for accessing and modifying element properties or methods outside the standard React data flow.
  • For more info, check my another blog.

What is React.forwardRef?

React.forwardRef is a function in React that allows components to forward a ref they receive to a child component. This is particularly useful when you want a parent component to interact with a specific child component instance.

Let』s see an example

import React, { forwardRef } from 'react';

const Input = forwardRef((props, ref) => {
  return (
    <input
      type="text"
      placeholder={props.placeholder}
      ref={ref}
    />
  );
});

export default Input;

In the above implementation we have created a React component names as Input. We have wrapped a functional component inside forwardRef function. Now let』s see how we pass the ref as prop to the Input.

import React, { useRef } from 'react';
import Input from './Input'; // Assuming the file is in the same directory

const ParentComponent = () => {
  const inputRef = useRef();

  useEffect(()=>{
    if (inputRef.current) {
      inputRef.current.focus();
    }
  }, []);

  return (
    <div>
      <Input ref={inputRef} placeholder="Enter text" />
    </div>
  );
};

export default ParentComponent;

Don』t skip, read this scenario.

Consider a situation where you are building a design system like React-Bootstrap. Assume that, you are currently building a Input Component. Since it』s essential for other developers, who may need ref object for accessing the underlying input element, you decided to add ref as a prop to your custom component. But what happens, boom, your code throws an error.

For example, let me remove the forwardRef from the input element.

import React from 'react';

const Input = (props) => {
    return (
        <input
            type="text"
            placeholder={props.placeholder}
            ref={props.ref}
        />
    );
}

export default Input;

Now let』s save it and run. What will happen? Any guess ?. The following line will throw an error

<Input ref={inputRef} placeholder="Enter text" />

**But why?

**Because ref is a reserved prop is React, just like reserved keywords in programming languages. React handles the ref prop specially, so by default you can』t override with your custom value.

Here』s the warning message: But in this case, it should be considered as Error message.

img

Now let』s fix this by using the clue given by first warning message. Now change the prop name from ref to myRef.

<Input myRef={inputRef} placeholder="Enter text" />

Also in the input component, change ref={props.ref} to ref={props.myRef}

import React from 'react';

const Input = (props) => {
    return (
        <input
            type="text"
            placeholder={props.placeholder}
            ref={props.myRef}
        />
    );
}

export default Input;

Wait, what happens if I use other prop names like myRef, customRef or ref1 ? will it work ?

Yes indeed, it works. You can use other names to forward you ref object in your custom react component.

Huh, then Why I need React.forwardRef ? You may have this question in your mind?

Your doubt has logic, but still you need forwardRef function. Let』s see why

What problem that forwardRef function solves ?

So if you not using forwardRef instead if you use any other name than ref for forwarding a ref object , then you need to mention it explicitly in the documentation. It will become harder for developers who are using your library, need to adapt to the new custom ref prop name. Also it violates the React standard way of coding.

How it solves the problem?

The forwardRef function will override the ref prop, which can』t be done implicitly, so that we can use the ref prop to send our custom ref object through it. So that there is no need of explicitly define the prop name for forwarding ref. Even in React』s official documentation itself, it dosen』t have this explanation atleast at the time of writing this blog. I hope it will be added soon.

Thanks for reading, your love and support means lot to me. Thank you, see you soon in another story.

React

Forwardref


下載開源日報APP:https://openingsource.org/2579/
加入我們:https://openingsource.org/about/join/
關注我們:https://openingsource.org/about/love/