Home > Blockchain >  Why is my line not breaking when I use "\n" in react?
Why is my line not breaking when I use "\n" in react?

Time:12-08

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

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

  • Related