Elyas Pourmotazedy
Elyas Pourmotazedy

Reputation: 732

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.

Upvotes: 1

Views: 1074

Answers (2)

harshith_98
harshith_98

Reputation: 1

Adding to the Brian's answer above, you can add listener on 'input' like

const el = document.getElementById('myText');
el.addEventListener('input');

to see the new value similar to react's onChange.

Upvotes: 0

Brian Thompson
Brian Thompson

Reputation: 14385

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>

Upvotes: 5

Related Questions