Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to target the value of a heading tag?

I want to target the value of h2 tag, like how you would do with an input.

const [text, setText] = useState("")

<input type="text" onChange={(e) => setText(e.target.value)} />

I tried <h2 onChange={(e) => setCheck(e.currentTarget.textContent)}>Text to target</h2> with no succes.

Which other ways are there to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

What you’re asking for doesn’t really make sense to me since anything in the <h2/> is going to be controlled by you in the component definition, but you can get a reference to the element through ref and then get its innerHTML through that.

const App = () => {
  return (
    <h2 ref={(el => console.log(el.innerHTML))}>This is text</h2>
  )
};

ReactDOM.render(
  <App/>,
  document.getElementById("app")
);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="app"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading