☰ See All Chapters |
How to access a DOM element - Reference a DOM element
When you want to let React handle all DOM manipulation, you can add a ref attribute to an element to access it directly in the DOM.
In the JSX of your component, you can assign the reference of the DOM element to a component property using this attribute:
Reference a DOM element in function component
import { useRef } from "react";
function DemoComponent() { const inputElement = useRef();
const focusInput = () => { inputElement.current.focus(); };
return ( <> <input type="text" ref={inputElement} /> <button onClick={focusInput}>Focus Input</button> </> ); } export default DemoComponent;
|
Reference a DOM element in class component
import React from 'react';
class DemoComponent extends React.Component { constructor(props) { super(props); this.inputElement = React.createRef(); } render() { return ( <div > <input type="text" ref={this.inputElement} /> </div> ) } }
export default DemoComponent; |
All Chapters