EN
React - get div reference
3
points
In this article we would like to show you how to get a div element reference in React.
In below example we create a reference using React.useRef hook. Then by a div ref property we attach the div reference to divRef.
That kind of reference let's us to access pure DOM element reference in React via divRef.current property.
// ONLINE-RUNNER:browser;
//Note: Uncomment import lines during working with JSX Compiler.
//import React from 'react';
//import ReactDOM from 'react-dom';
const divStyle = {
height: '20px',
background: 'yellow',
border: 'solid',
borderColor: 'red'
};
const App = () => {
const divRef = React.useRef();
return (
<div>
<div ref={divRef} style={divStyle}>
<b>My div</b>
</div>
<br />
<button onClick={() => console.log(divRef.current)}>Check reference</button>
<button onClick={() => console.log(divRef.current.innerText)}>Check innerText</button>
<button onClick={() => console.log(divRef.current.innerHTML)}>Check innerHTML</button>
<button onClick={() => console.log(divRef.current.outerHTML)}>Check outerHTML</button>
</div>
);
}
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);