top of page
Logo der Online Agentur mdwp

ForwardRef

React.forwardRef is a method in React that allows you to access and interact with a child component directly from a parent component. This means you can modify the child's properties, call its methods, or access its elements.

Normally, you wouldn't interact with a child component directly. But sometimes it's necessary, especially when you're dealing with UI elements like inputs, forms, or animations.

React.forwardRef creates a ref (reference) to a DOM element or class component in the child component, which you can then use in the parent component.

You create a forwarded ref like this:

```jsx
import React, { forwardRef } from 'react';

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

export default MyComponent;
```

Then you can use this ref in parent component like so:

```jsx
import React, { createRef, Component } from 'react';
import MyComponent from './MyComponent';

class ParentComponent extends Component {

myRef = createRef();

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

render() {
return <MyComponent ref={this.myRef} />;
}
}

export default ParentComponent;
```

In this example, `ParentComponent` is able to directly manipulate the input field created in `MyComponent` via the forwarded ref. Specifically, it sets focus to the input field right after it gets loaded on the page. This wouldn't be possible without `forwardRef`.

bottom of page