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

150
Vistas
Why is my line not breaking when I use "\n" in react?

I am trying to use this hook:

useEffect(() => {
  var arrText = txt.split('*');
  arrText.map((line, index) =>
    setTimeout(() => {
      setTexto((prev) => {
        return (prev += line + '\n');
      });
    }, 300 * index),
  );
}, []);

And it simply rejects my \n and if I try to return JSX (the line in a paragraph), it becomes a [object object]

Can you please help me? <3

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The problem is, unless you're trying to display a newline in a pre tag, it will be ignored in the browser. You could however store the text content in the state in an array, update that using the setTimeout and render this state. You can use <p> tags or <br> tags to display the text on new lines.

Also, you shouldn't use map() as it creates a new array. You could use forEach() or a simple for loop instead.

let txt =
  'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Tenetur sapiente incidunt molestias beatae voluptas fuga repellendus sit nihil voluptate laudantium delectus aliquam, nulla non suscipit a ea natus voluptatem distinctio!';

function App() {
  let [texto, setTexto] = React.useState([]);

  React.useEffect(() => {
    txt.split(' ').forEach((line, index) =>
      setTimeout(() => {
        setTexto((prev) => {
          return [...prev, line];
        });
      }, 300 * index)
    );
  }, []);

  return (
    <div>
      {texto.map((word, i) => (
        <p key={i}>{word}</p>
      ))}
    </div>
  );
}

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);
<div id="root"></div>
<script src="https://unpkg.com/react/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.production.min.js"></script>

You shouldn't store HTML tags in your state as you will need to use dangerouslySetInnerHTML.

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