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

165
Visualizações
React - Adding a line break;

So I have a function for adding a line break every 60 characters. Now what I don't understand is why the \n doesnt work.

function countStr (str1){
    let str2="";
    let charCount=0;
    for(let i=0; i<str.length; i++){
            if(i%60===0){
            str2=str2.concat(str1.substring(charCount,i));
            str2+="\n";
            charCount=i;
            
        }
    }
    return str2;
}


const About = () =>{
 
    return(

        <div className="about">
         <h2>I'm Gal</h2>
         <p>{changedStr}

</p>
        </div>

    );
}
export default About;
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Loop over the input string. If the current iteration is at i % 20 (and also not zero) add a line-break. Add the character from the input string.

In your component that's rendering the string you need to add some CSS to that element so it prints properly: white-space: pre-line.

function countStr(str) {
  let out = '';
  for (let i = 0; i < str.length; i++) {
    if (i % 20 === 0 && i !== 0) out += '\n';
    out += str[i];
  }
  return out;
}

// Example string of 220 characters
let str = '';

for (let i = 0; i < 220; i++) {
  str += '1';
}

function Example({ str }) {
  return (
    <div>{str}</div>
  );
};

ReactDOM.render(
  <Example str={countStr(str)} />,
  document.getElementById('react')
);
div { white-space: pre-line; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

Use this simple function

function countStr(str) {
  let str2 = '';
  while (str.length > 0) {
    str2 += str.substring(0, 60) + '\n';
    str = str.substring(60);
  }
  return str2;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

If you're using it in react and it's going on to the web then it's because you probably need a <br/> not a \n

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