Skip to content
Related Articles

Related Articles

Improve Article
How to access a DOM element in React ?
  • Last Updated : 19 Feb, 2021

In React we can access the DOM element using Refs. Refs provide a way to access DOM nodes or React elements created in the render method.

Creating Refs: Refs are created using React.createRef() and attached to React elements via the ref attribute. 

class App extends React.Component {
constructor(props) {
  super(props);
  //creating ref
  this.myRef= React.createRef();
}
render() {
//assigning ref
  return (
  <div >
  <input ref= {this.myRef } />
  </div>
  )
}
}

Accessing Refs: When we assign a ref to an element in the render, then we can access the element using the current attribute of the ref.

const element = this.myRef.current;

Creating React Application:

Step 1: Create a React application using the following command:



npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Project Structure: It will look like the following.

Filename- App.js: Open App.js file situated inside an src folder edit it as:

Javascript




import React from 'react'
  
class App extends React.Component {
  
    constructor(props) {
        super(props);
         
        this.myRef = React.createRef();
      }
       
    handleClick = () => {
  
          
        this.myRef.current.value = "you clicked on button";
    }
    
    render() {
      return (
        <div>
        <input ref = {this.myRef}/>
          <button 
            onClick = {this.handleClick}
          > click me </button>
        </div>
      );
    }
  }
  
  export default App;

Output:

My Personal Notes arrow_drop_up
Recommended Articles
Page :