Home > Mobile >  How to target the value of a heading tag?
How to target the value of a heading tag?

Time:08-26

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?

CodePudding user response:

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>

  • Related