Languages
[Edit]
EN

React - get div reference

3 points
Created by:
maryam
1181

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);
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - get div reference
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join