What is a ref ? How do you use it ?

  • It is a function provided by React to access the DOM element and the React element that you might have created on your own.
  • In React, a ref is a reference to a DOM element.
  • It can be immediately placed in a variable.
  • They are created with the help of useRef
  • This variable is then passed to a given React element (not a component) to get a reference to the underlying DOM element (that is, div, span, and so on).
  • Properties are now available on the element itself.
  • Refs are often referred to as an “escape hatch” to be able to work with a DOM element directly.
  • They allow us to do certain operations that can’t be done through React otherwise, such as clearing or focusing an input.

For Example,

[pastacode lang=”markup” manual=”%2F%2F%20using%20refs%0A%0Aclass%20App%20extends%20React.Component%20%7B%0A%0A%C2%A0constructor()%7B%0A%0A%C2%A0%C2%A0super()%3B%0A%0A%C2%A0%C2%A0this.state%20%3D%20%7B%20sayings%3A%20%22%22%7D%3B%0A%0A%C2%A0%7D%0A%0A%C2%A0update(e)%7B%0A%0A%C2%A0%C2%A0this.setState(%7B%20sayings%3A%20this.refs.anything.value%7D)%3B%0A%0A%C2%A0%7D%0A%0A%C2%A0render()%7B%0A%0A%C2%A0%C2%A0return%20(%0A%0A%C2%A0%C2%A0%C2%A0%3Cdiv%3E%0A%0A%C2%A0%C2%A0%C2%A0%C2%A0Welcome%20to%20Kaashiv%20%3Cinput%20type%3D%22text%22%20ref%3D%22anything%22%0A%0A%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0onChange%20%3D%20%7Bthis.update.bind(this)%7D%2F%3E%0A%0A%C2%A0%C2%A0%C2%A0%3Cbr%2F%3E%0A%0A%C2%A0%C2%A0%C2%A0%3Cem%3E%7Bthis.state.sayings%7D%3C%2Fem%3E%0A%0A%C2%A0%C2%A0%3C%2Fdiv%3E%0A%0A%C2%A0%C2%A0)%3B%0A%0A%C2%A0%7D%0A%0A%7D%0A%0A%C2%A0ReactDOM.render(%3C%20App%20%2F%3E%2C%20document.getElementById(‘root’))%3B%0A%0A%C2%A0″ message=”” highlight=”” provider=”manual”/]

 Output:

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like

What is Prop Drilling ?

We pass a prop with another component with the help of all the components that come between, this method is known as prop drilling. Prop drilling is basically a situation…
View Answer

What is React DOM ?

It is an object which exposes a number of top level APIs to interact with the browser DOM. It provides DOM-specific methods that can be used at the top level…
View Answer

What is Flux ?

It is an application architecture that Facebook makes use of internally for constructing the client-side web application with React . It is a programming concept, where the data is a…
View Answer