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.
xxxxxxxxxx
1
//Note: Uncomment import lines during working with JSX Compiler.
2
//import React from 'react';
3
//import ReactDOM from 'react-dom';
4
5
const divStyle = {
6
height: '20px',
7
background: 'yellow',
8
border: 'solid',
9
borderColor: 'red'
10
};
11
12
const App = () => {
13
const divRef = React.useRef();
14
return (
15
<div>
16
<div ref={divRef} style={divStyle}>
17
<b>My div</b>
18
</div>
19
<br />
20
<button onClick={() => console.log(divRef.current)}>Check reference</button>
21
<button onClick={() => console.log(divRef.current.innerText)}>Check innerText</button>
22
<button onClick={() => console.log(divRef.current.innerHTML)}>Check innerHTML</button>
23
<button onClick={() => console.log(divRef.current.outerHTML)}>Check outerHTML</button>
24
</div>
25
);
26
}
27
28
const root = document.querySelector('#root');
29
ReactDOM.render(<App />, root);