forwarding refs in react js example

Forwarding Refs in React js Example

When we use Forwarding Refs in React js Example, our default thinking should be that we do not incorrectly modify the DOM, but instead pass the props and re-donate the part. But sometimes there are situations where important actions are needed.

Forwarding refs in react js provides access to React objects (or DOM nodes) created in the form of render ().

When parental parts need to work with children’s things, we always use props. That’s where forwarding refs in react js get to shine.

Read Also :  How to Use React Context API with Example

Forwarding Refs in React js Example

Index.js

import React, { Component } from 'react'
import App from './App'
import ReactDOM from 'react-dom'

export default class Demo extends Component {
  render() {
    return (
      <div>
        <App />
      </div>
    )
  }
}

ReactDOM.render(<Demo />,document.getElementById("root"));

React.createRef()

Refs can be created by using the React.createRef() function and attached to an HTML element in a React component via the ref attribute.

Read Also :  How to Use Strict Mode in React

App.js

import React, { Component } from 'react'
import Parent from './Parent'

export default class App extends Component {
    render() {
        return (
            <div>
                <h1>App Component</h1>
                <Parent />
            </div>
        )
    }
}

Parent.js

import React, { Component } from 'react'
import Child from './Child'

export default class Parent extends Component {
    firstRef = React.createRef();
    focusTextInput =() =>{
        this.firstRef.current.style.color="red";
        this.firstRef.current.focus();
    }

    render() {
        return (
            <div>
                <Child ref={this.firstRef}/>
               
                <input
                    type="button"
                    value="Focus the text input"
                    onClick={this.focusTextInput}
                    />
            </div>
        )
    }
}

Child.js

import React from 'react'
const Child = React.forwardRef( (props,ref) => {
    return(
        <input type="text" ref={ref} />
    )
   }
)

export default Child;