Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

162
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda