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

159
Visualizações
Visualize onkeypress line breaks in textarea with REACT

what is a valid approach to visualize a text created inside a textarea element with the correctly assigned line breaks?

As soon as I input a line break by pressing Enter key, I can see that this is displayed inside the textarea correctly but when I visualize the output in another element, the line break appears as a space. The data is also saved in my database without any line breaks.

I have attached a sample code to the link below: https://codesandbox.io/s/busy-hodgkin-1oujz?file=/src/App.js

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The easiest way would be through CSS, by following:

...
<div className="App">
  <div className="wrapper">
    <div>
      <p class='formatted'>{text}</p>
    </div>
...

And then: .formatted { white-space: pre; }

Another way would be using dangerouslySetInnerHTML:

...
<div className="wrapper">
  <div>
    <p
      dangerouslySetInnerHTML={{
        __html: formattedText,
      }}>
    </p>
  </div>
...

And the logic to handle that would be:

const [text, setText] = useState('');
const [formattedText, setFormattedText] = useState(text);

const handleTextInput = ({ target }) => {
  const { value } = target;
  const formattedValue = value.replace(/\n/g, '<br />');

  setText(value);
  setFormattedText(formattedValue);
};
about 4 years ago · Juan Pablo Isaza Relatório

0

There's some possible approachs to your problem. In few words, \n new line characters on textarea does not work on plain html. Instead, we could use <br />.

Instead of simply rendering text as it's stored, you could split into new lines and render <br /> in its place:

      <p>
        {text.split('\n').map((subtext) => (
          <>
            {subtext}
            <br/>
          </>
        ))}
      </p>
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