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

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

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 Denunciar

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 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