Wednesday, November 20, 2024
Google search engine
HomeLanguagesHow to access a DOM element in React ?

How to access a DOM element in React ?

React is a popular JavaScript library for building user interfaces. It provides a component-based architecture and a virtual DOM, which allows for efficient and flexible rendering of UI elements. In most cases, React manages the rendering of components and updates the DOM automatically. However, there are situations where you may need to access a specific DOM element directly. In this article, we’ll explore Refs to access a DOM element in React. 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:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments