开源日报每天推荐一个 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.
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.
下载开源日报APP:https://openingsource.org/2579/
加入我们:https://openingsource.org/about/join/
关注我们:https://openingsource.org/about/love/