Friday, August 10, 2018

forwardRef Refs example in React

Ref forwarding is an approach by with React allows us to create a Ref in a parent component and forward the same to a nested child component. The forwarded ref is attached to a DOM node in the child component, once it is attached the parent component can have direct access to the DOM node in the child component.

Ref forwarding typically not necessary for most components in the application, since React components hide their implementation details, including their rendered output. However the forwardRef approach can be used for features like setting focus, clearing text etc.

In the below example we create a ref "myRef" in the parent component and pass the same to "ChildComponent", this component attaches the ref to a text-box. The parent component can now access the value in the text-box using this.myRef.current.value. In this example we have a button in the parent component, on clicking the button we get the value from the text-box and display it in the parent component.

import React, {Component} from 'react';
import ReactDOM from 'react-dom';

const ChildComponent = React.forwardRef((props, ref) => (
  <div>
    <input ref={ref}></input>
  </div>
));

class HelloForwardRef extends Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
    this.state = {
refValue: ""
     };
     this.handleClick = this.handleClick.bind(this);
  }

   handleClick() {
    this.setState({refValue : this.myRef.current.value});
  }

  render() {
return (
  <div>
<div>
<ChildComponent ref={this.myRef}/>
<button onClick = {this.handleClick}> Click </button><br/><br/>
Ref value from Child Component:  <b>{ this.state.refValue }</b>
</div>
  </div>
);
  }
}

ReactDOM.render(<HelloForwardRef />, document.getElementById('app'));

Output:


Search Flipkart Products:
Flipkart.com

No comments: