React forwardRef Example
Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
// Filename - App.js import React from 'react' class App extends React.Component { constructor(props) { super (props) this .aRef = React.createRef() } render() { return ( <> <Counter ref={ this .aRef} /> <button onClick={() => { console.log( this .aRef) }}> Ref </button> </> ) } } const Counter = React.forwardRef((props, ref) => { class Counter extends React.Component { constructor(props) { super (props) this .state = { count: 0 } } render() { return ( <div> Count: { this .state.count} <button ref={ref} onClick={() => this .setState( { count: this .state.count + 1 })}> Increment </button> </div> ) } } return <Counter /> }) export default App |
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Explanation:
The explaination to above examples is as follows:
- The counter, residing within a function, provides closures to access props and ref parameters, ensuring effective encapsulation.
- The Counter component renders with a ref, establishing a connection to the button element using the ref attribute.
- The Counter component passes its ref to a child component, allowing seamless access to the button element.
- The App component renders the Counter component, initializing a ref and logging the HTMLButtonElement value on button click.
Reference: https://reactjs.org/docs/forwarding-refs.html
React forwardRef
React forwardRef allows parent components to move down (or “forward”) refs to their children. It gives a child component a reference to DOM entity created by its parent component in React. This helps the child to read and modify the element from any location where it is used.
Table of Content
- React Forwarding Refs
- React forwardRef
- How does forwardRef work in React ?
- React Forwarding Refs Example:
React forwardRef allows to expose a DOM node to Parent Component. It is a method that lets React forward the React refs to the child component. This technique is Forwarding Ref.
Syntax:
React.forwardRef((props, ref) => {})
Parameters:
- It takes a function with props and ref arguments.
Return Value:
- This function returns a JSX Element.