Quick Contact


    React Refs

    Refs make possible to access Dom nodes directly within react. Suppose you want text input to be focused in Form so achieve it with Refs. So create new file refs.js. In file use input element. It can be done in three simple steps.

    First step is to create Ref using react ref method. So in this component add constructor within constructor create new property ‘this.inputref’. To this property assign react.createRef(). Second method is to attach ref to input element in render method. Third method is to call focused method into this elementas-:

    		Import React, {Component} from ‘react’
    		class RefsDemo extends Component {
    		constructor(props) {
    		super(props)
    		this.inputRef = React.createRef()
    		}
    		componentDidMount() {
    		this.inputRef.current.focus()
    		console.log(this.inputRef)
    		}
    		Render()
    		Return(
    		< div>
    		< input type=”text” ref={this.inputRef} />
    		< /div>
    		)
    		}
    		}
    		Export default RefsDemo
    	
    React Refs
    React Refs

    As output is as below where first message arrives and when you click OK, then the form will be shown of number increment.

    React Refs
    React Refs

    As when you click on increment sign again message arrives and after click OK again , only then number will be increment.

    React Refs
    React Refs

    On button click access “ref” function which is created in following code and you can increment the value without rendering component again and again. When ref is pass to element that element is accessible using an attribute call as current.

    React Refs

    So here this.quantityRef method is used where element is accessible through ref.

    componentDidMount(){

    this.usernameRef.current.focus();

    React Refs

    Copyright 1999- Ducat Creative, All rights reserved.