Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
add onChange to input in string in react

I'm using react for my project and I have the string below.

const text= "<p><strong>Late 19th Century</strong></p><ul><li>in Yellowstone Park, every type of <input type="text" /> was prohibitedas</li></ul>"

and I use :

 <div  dangerouslySetInnerHTML={{ __html: text }}></div>

how to handle onChange input when I use dangerouslySetInnerHTML on string in react.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

At this point you're working with native HTML, it is no longer React and you cannot treat it as such. You'll either have to go down the rabbit trail of manually attaching event listeners to the set HTML or just use React as it's intended.

NOTE: I'm assuming you have a good reason to do this. Otherwise, I do not recommend this for normal use-cases in React.

That said, here is a way you could still use the string of HTML with React's state.

For simplicity I added an id attribute to the input in your string. Also note that, because of the difference in when the native DOM change event fires vs the React change event, you have to click out of the input to see the new value.

const {useState, useEffect} = React;

const text= '<p><strong>Late 19th Century</strong></p><ul><li>in Yellowstone Park, every type of <input id="myText" type="text" /> was prohibitedas</li></ul>'

const Example = () => {
  const [value, setValue] = useState('');
  
  useEffect(() => {
    const el = document.getElementById('myText');
    
    el.addEventListener('change', (e) => setValue(e.target.value));
  }, []);
  
  console.log('value', value);
   
  return <div dangerouslySetInnerHTML={{ __html: text }}></div>;
}

ReactDOM.render(<Example />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!