Why, exactly, do we need React.forwardRef? - reactjs

Let's say I have a component with a scrollable subcomponent, and I want to expose the ability to scroll:
const MyComponent = (props) => {
return <ScrollView ... />
}
I want to be able to do
<MyComponent ref={myRef} />
...
myRef.scrollTo({x: 0});
So I need a way to forward the ref to the <ScrollView>. Let's try putting the ref on the props:
const MyComponent = (props) => {
return <ScrollView ref={props.scrollRef} ... />
}
...
<MyComponent scrollRef={myRef} />
...
myRef.scrollTo({x: 0});
I just tried that with React Native on iOS, and it indeed works. I see several advantages over React.forwardRef:
Simpler, because I don't need to use another React API.
Works also if there is more than one child who needs ref forwarding.
Seems to me that this approach is
What's the advantage of React.forwardRef? Why was it added in React 16.3?

Note that there is no difference between using another named prop like innerRef FOR FORWARDING, it works the same.
Refactoring class components
Since React moved toward function components (hooks) you might want to refactor the class component code to a function component without breaking the API.
// Refactor class component API to function component using forwardRef
<Component ref={myRef} />
React.forwardRef will be your only option (further explained in details).
Clean API
As a library author you may want a predictable API for ref forwarding.
For example, if you implemented a Component and someone wants to attach a ref to it, he has two options depending on your API:
<Component innerRef={myRef} />
The developer needs to be aware there is a custom prop for forwarding
To which element the innerRef attached? We can't know, should be mentioned in the API or we console.log(myRef.current)
<Component ref={myRef} />
Default behavior similar to ref prop used on HTML elements, commonly attached to the inner wrapper component.
Notice that React.forwardRef can be used for function component and HOC (for class component see alternative below).
Ref forwarding is not limited to DOM components. You can forward refs to class component instances, too.
For function components, forwardRef sometimes comes with useImperativeHandle combo (in class component you just call the class methods on ref instance: ref.current.myAttr().
// Same usage
<Component ref={myRef} />
const Component = React.forwardRef((props, ref) => {
// you can forward ref <div ref={ref} />
// you can add custom attributes to ref instance with `useImperativeHandle`
// like having ref.myAttribute() in addition to ones attached to other component.
});
Important behavior of ref prop without forwardRef.
For the class component, this code alone will attach the ref to CLASS INSTANCE which is not useful by itself and need another ref for forwarding:
// usage, passing a ref instance myRef to class Component
<Component ref={myRef} />
Full example, check the logs:
// We want to forward ref to inner div
class ClassComponent extends React.Component {
innerRef = React.createRef();
render() {
// Notice that you can't just `this.props.ref.current = node`
// You don't have `ref` prop, it always `undefined`.
return <div ref={this.innerRef}>Hello</div>;
}
}
const Component = () => {
const ref = React.useRef();
useEffect(() => {
// The ref attached to class instance
console.log(ref.current);
// Access inner div through another ref
console.log(ref.current.innerRef);
}, []);
return <ClassComponent ref={ref} />;
};
In function components, it won't even work because functions don't have instances.
By default, you may not use the ref attribute on function components because they don’t have instances. [1]
forwardRef.
Refs and the DOM.
Why we need ref forwarding?

Related

Composition In React with params

I am trying to create an architecture that in some way imitates the slots from VUE.
The idea is for the parent component to be able to inject some props into the component and the child can inject the rest of the props.
This is how I tried to approach this problem, unfortunately this approach will not work because the compontent will be "monut" every time the parent re-render takes place.
Filters = (prams) => {
useEffect(()=>{ //RENDER ALL THE TIME },[])
...
}
ParentComponent = () => <ChildComponent Filters={(props) => <Filters propA={"A"} />}
ChildComponent = (props) => {
const Filters = props.Filters;
render(<Filters probB="B" />)
}
I know, I can use useCallback for ((props) => <Filters propA={"A"} />), but only it will help only if what I want to pass to "propA" is steady.
I want to "manage" <Filters /> component in parent, so that the child does not have to handle Filters logic (props).
React gives you proper API to do most things. Using it forces you into certain paradigms that are proven to work well.
You should probably have a look at the Context and Memo APIs from React.
Or if you have to select and update state from multiple components, you might wanna have a look at libraries that provide global state, like Redux and Recoil.
Context example
// The shape
interface ContextProps {
myProp: string
}
// The context
export const MyContext = React.createContext<Partial<ContextProps>>({
myProp: 'nothing'
});
// The provider
<MyContext.Provider value={{ myProp: 'override' }}>
{children}
</MyContext.Provider>
// Consumer
const { myProp } = useContext(MyContext)
In some case you can also use useMemo or React.memo and use your own custom compare function if needed to prevent re-renders in very specific situations.

How to explicitly create an optional property in a React component when it is not specificied?

In a React component I need a ref to the HTML element I use for some manual processing (e.g. to listen to resize events). I can do that by defining a ref member in my component and set that in the render method:
render() {
return <div ref={this.myRef} />;
}
However, sometimes the owner of this component also needs this ref for other work (e.g. dynamic handling of certain other events). It makes sense to use the same ref here, so I added a property to the component:
render() {
const { innerRef } = this.props;
return <div ref={innerRef} />;
}
The problem is now that the parent component not always uses the inner ref, so it doesn't specify it when creating the inner component. In order to maintain the functionality of the inner component I want to explicitly create the ref if not given by the parent like:
public constructor(props: MyProps) {
super(props);
if (!props.innerRef) {
props.innerRef = React.createRef<HTMLElement>();
}
}
However, that's not accepted because props is read only. What other approach could I take to accomplish this explicit init, if not provided?
Note: I tried to use the static defaultProps to provide such a default, but defaultProps is used for all instances of the class, so they all share the same default ref then. Hence this is not a good approach.
Instead of trying to directly assign a new value to props, check if the innerRef is available from the props and if not pass an internally created ref to the div like this.
<div ref={innerRef || internallyCreatedRef} />

Passing one Prop vs Many Props vs Nested Components in React?

This is a part of Think in React.
Thinking in React is the hard part for me because I see many developers do React with different mindsets.
When I was writing code for the Notification component that will be used by developers, suddenly I've noticed that there are different experiences to use the component:
Passing many Props like Bootstrap
<Notification
title="New Feature"
body={message}
action={action}/>
Passing one Prop as an Object
const data = {
title:"",
subtitle:"",
message:""
}
<Notification data={data}/>
Passing nested Children
<Notification>
<Title></Title>
<Body><Body/>
<Action><Action>
</Notification>
I followed the passing nested Children because ( I guess) It seems if I scale the component, I don't need to provide a Bootstrap-like experience for the developers.
import React from "react"
import { Wrapper, Text } from "./Styled"
const Body = ({ message }) => (
<Wrapper>
<Text>{message}</Text>
</Wrapper>
)
export default Body
The problem is I'm thinking about it is when I want to scale the Component and let's say adding 3 additional features that require 3 additional props
I'm confused about the reasons why each approach might be chosen, and what's the "best" developer experience.
To answer this question let's review all possibilities given React Element and a Function Component:
const c1 = <div>React Element</div>;
const C2 = () => <div>Function Component</div>;
Notice that from performance perspective, every component can be memoized and not cause useless renders.
Pass React element through props
const ObjectProps = ({ component }) => {
console.log("render object props");
return component;
};
<ObjectProps component={c1} />
Pros
Simple.
Lets you define the exact usage of passed component (contract).
For example you might decide "messages" have to be on top of "actions"
Cons
No lazy rendering
Passing heavy component may cause performance issues.
Hard to inject props (need to use React.cloneElement).
As a library writer you would like to inject your styles and refs.
Passing Function Component
const FunctionComponentProps = ({ FunctionComponent }) => {
console.log("render function component");
return <FunctionComponent />;
};
<FunctionComponentProps FunctionComponent={C2} />
Pros
Lazy rendering.
Easy to pass props and inject props for inner implementation.
Lets you define the exact usage of passed component (contract).
Cons
Confusing
Children Render
const ChildrenRender = ({ children }) => {
console.log("render function component");
return children;
};
<ChildrenRender>
{c1}
<C2 />
</ChildrenRender>
Pros
No restriction for the developer (no contract)
Cons
Hard to inject children (need to use React.Children API + React.cloneElement combo)
No contract
The developer might pass "buttons" and then "messages" and break the view.
Implementing ChildrenRender usually comes with component instances which results a minimal "contract" mentioned above.
const ChildrenRender = ({ children }) => {...};
ChildrenRender.InnerComp1 = <SomeComponent .../>
ChildrenRender.InnerComp2 = <SomeComponent2 .../>
<ChildrenRender>
<ChildrenRender.InnerComp1>{c1}</ChildrenRender.InnerComp1>
<ChildrenRender.InnerComp2><C2/></ChildrenRender.InnerComp2>
</ChildrenRender>
In Conclusion
It heavily depends on the component's usage, usually the hybrid approach suits well - passing components through props and add an option for passing children too.
Another technique is Render Props.

React implicit mapping mechanism

I am going through the tutorial:
https://www.robinwieruch.de/gentle-introduction-higher-order-components/
And they have such kind of statements:
const withTodosNull = (Component) => (props) =>
!props.todos
? null
: <Component { ...props } />
As I understand Component is passed to the function, then its props get implicitly taken and fed into the return function. I do not understand how the React is doing that. I would honestly expect something like (Component) => (Component.props). What is the mechanism for this? Is it mapped correctly only if we supply the argument as props or we can supply any name? Is there a specific name for such implicit assignment?
Update
Maybe I was not clear enough, but what I am really interested in is from where props appear in the inner function if they are not passed to the previous, outer, function. I understand how the HOCs work, how to think about them, but this moment is very unclear and what in React is doing that? Is there some kind of an engine running behind the scenes, idk...
This technique is called higher-order components (HOCs) and is a way of extending components with some extra functionality.
It might look easier at first if you rewrite it using regular functions instead of arrow functions:
function withTodosNull(Component) {
return function(props) {
if (!props.todos) {
return null;
} else {
return <Component {...props} />
}
}
}
withTodosNull takes in a component and returns a new component. If this new component that is returned gets a todos prop, the component passed into the HOC will be rendered with all the props. If todos is not given as a prop, null will be rendered.
It will be probably easier to understand if we rewrite arrow functions using classic function():
function withTodosNull(Component) {
return function(props) {
if (!props.todos) {
return null;
}
return <Component {...props} />;
}
}
The inner unnamed function is a functional component. It takes properties and renders either as null or as Component.
The outer function is something called high-order-component (HoC). It is a function, that wraps a component and returns a new component.
There is no connection between Component and props. They are only parameters of two different functions.
Specifically, when you call:
class MyComponent: React.Component {
}
const myComponentWithTodosNull = withTodosNull(MyComponent);
it is the same as writing:
const myComponentWithTodosNull = props => {
if (!props.todos) {
return null;
}
return <MyComponent {...props} />;
}
Higher-Order Components are functions that "enhance" components passed as a parameter. To understand where the props are coming from let's see what would it look like to use such component.
There's our basic component, which will be passed to the HoC:
function TodoList(props) {
return (
<div>We have {props.todos.length} tasks to do!</div>
);
}
And now, we can use our HoC to create new "enhanced" component, which prevents displaying this message, when there aren't any tasks left:
const EnhancedTodoList = withTodosNull(TodoList);
Then we can use this new component, to render the message (or not, if there aren't any tasks):
<EnhancedTodoList todos={someTodos} />
As you can see, EnhancedTodoList is the first component, which gets todos. Then it decides if props should be passed to TodoList, or should it return null, when there aren't any todos.
Todos are passed explicitly from the component which renders the HoC. EnhancedTodoList acts just like a filter for TodoList.

GraphQL HOC messes with ref to children | React

I am using React and Apollo for my project.
I got this in my component MenuModal:
onClick = () => {
console.log(this.child)
this.child.onSubmit(); // do stuff
};
render() {
return (
<Modal.Content scrolling>
<MenuEdit
ref={ref => (this.child = ref)} // Using ref to access it's properties
selectedValues={selectedValues}
match={match}
menu={menu}
/>
My component MenuEdit has a function defined in class:
onSubmit = values => {
console.log('calling inner form submit', values);
if (this.child) {
this.child.submitFromOutside();
}
};
I should be able to call onSubmit from MenuModal right?
But I am currently getting this:
And when I console.log this.child in my onClick function I can see this:
So there's no onSubmit function there. When seeing GraphQL I wondered if it had something to do with me exporting the component with the graphQL HOC.
export default compose(
graphql(UPDATE_MENU, { name: 'updateMenu' }),
withApollo,
withRouter
)(MenuEdit);
And when I changed it just to:
export default MenuEdit;
I can see my function
So I wonder how I write my export so I still can access my function in my child. Thanks.
The HOC wrapps your component into another component. You can see this in the React devtools. You will see that the component renders a component around your wrapped component. Something like this
<Apollo(ChildComponent)>
<ChildComponent />
</Apollo>
Your ref then points to the Apollo(ChildComponen) element instance.
What you are doing here looks like an antipattern to me. In React we usually don't call functions on rendered elements (except sometimes DOM elements). The idea is rather that children call functions of their parents by receiving them as properties. The best thing in your case is to get rid of the reference and move your state and actions up the component chain. Alternatively you can use the new render prop style in react-apollo.
There was a contribution to the Apollo repository to address this issue...
https://github.com/apollographql/react-apollo/pull/410
Wrapping your component export like this withApollo(Component, { withRef: true }) will expose your child methods. Accessible using ref.current.wrappedInstance.

Resources