Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda