1

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.

2
  • Why are you injecting the HTML like this and not just using JSX? I don't see anything specific that would preclude you from listing the HTML elements in a JSX block. Commented Sep 9, 2021 at 17:42
  • I get it from API that was created with a rich text editor. Commented Sep 10, 2021 at 11:40

2 Answers 2

5

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.