Ref is a feature in Reactjs, which allow us to directly access the DOM object. To make this clear first create simple input component.
class InputRef extends Component {
constructor(props) {
super(props)
}
render() {
return (
<div>
<input type="text" } />
</div>
)
}
}
Following steps are required to use the ref in your class
- Create ref in the constructor
- Refer the ref in input
Create ref
We can create ref using the React.createRef() method as follows
this.input_ref=React.createRef()
Make a reference
We can access the DOM using the ref object and assign it to the input tags ref props.
<input type="text" ref={this.input_ref} />
componentDidMount()
This is a Lifecyle method of the component which occurs once when the component loaded or page refreshed. In this method we can use the focus method to focus the text input as follow
componentDidMount(){
this.input_ref.current.focus()
}
Ref make to possible to access the current state of the object we referring by using current object.
Here is the complete code for the component
class InputRef extends Component {
constructor(props) {
super(props)
this.input_ref=React.createRef()
}
componentDidMount(){
this.input_ref.current.focus()
}
render() {
return (
<div>
<input type="text" ref={this.input_ref} />
</div>
)
}
}
export default InputRef