Refs in React

From Logic Wiki
Jump to: navigation, search


Refs are used to access DOM elements

On top of the file create a ref first

username = React.createRef();

Then assign it to a form element

<input ref={this.username} is="username" type="text">

and use it like

const username = this.username.current.value;


it can be used to create a focus for example

componentDidMount(){
  this.username.current.focus();
}

of course we can just use autoFocus attribute instead.


See : https://codewithmosh.com/courses/357787/lectures/5707067