React JS Ref And Ref With Class

React Refs are a useful feature that acts as a means to reference a DOM element or a class component from within a parent component.

We can get more idea by looking below example. you can put this file in /src/components folder and put in /src/App.js file.

1. RefReact

RefReact
import React, { Component } from 'react'; class RefReact extends Component { constructor(props) { super(props) this.inputRef = React.createRef(); } componentDidMount () { this.inputRef.current.focus(); console.log(this.inputRef); } clickHandler = () => { alert(this.inputRef.current.value); } render() { return( <div> <input type='text' ref={this.inputRef} /> <button onClick={this.clickHandler}>Click</button> </div> ); } } export default RefReact;

In above code, in constructor we create a ref and assign it to inputRef. now inputRef given to input element ref. While run this code, It will show focused on textbox and one object in console panel, which have our textbox. now, type something in textbox and click on button shows value of textbox in alert.

Ref with Class

Now we will understand by parent and child components

1. ParentComponent

ParentComponent
import React, { Component } from 'react'; class ParentComponent extends Component { constructor(props) { super(props) this.componentRef = React.createRef(); } clickHandler = () => { this.componentRef.current.focusInput(); } render() { return( <div> <RefReact ref={this.componentRef} /> <button onClick={this.clickHandler}>Focus Input</button> </div> ); } } export default ParentComponent;

2. RefReact - Child component

RefReact - Child component
import React, { Component } from 'react'; class RefReact extends Component { constructor(props) { super(props) this.inputRef = React.createRef(); } focusInput () { this.inputRef.current.focus(); } render() { return( <div> <input type='text' ref={this.inputRef} /> </div> ); } } export default RefReact;

In above code, focusInput is a method in RefReact - child component which is called from parent component by using componentRef. When we click on button it will focus the textbox.

 

← Previous

Next →