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

319
Visualizações
Hide and show number of characters in <p> - React

I have a <p> with a paragraph inside and a button. I would like to display 40 characters when I click the button. And display the entire paragraph if I click on it again.

Here is my code :

const [showText, setShowText] = useState(false)

<div>
  <ImCross onClick={() => setShowText(!showText)} />
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque consectetur debitis deserunt dicta dignissimos est et excepturi facere facilis fugit id in, ipsa quae reiciendis repellendus suscipit unde veniam voluptas.</p>
</div>

<ImCross /> is the button to hide and show text. Now I'm totaly lost on how can I get the .length of the <p>, and change the number displayed on click.

Any help ?

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

0

You could create a truncate function, and use it when the show more button has been clicked.

I found a truncate function from this answer.

So your code might look something like:

// create a function that only returns a certain amount of characters.
// i've just used 5 as it's what the original stack question did
const truncate = (input) =>
  input.length > 5 ? `${input.substring(0, 5)}...` : input;

function App() {
  // create a toggle state
  const [showTruncate, setShowTruncate] = useState(true);

  let content =
    "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque consectetur debitis deserunt dicta dignissimos est et excepturi facere facilis fugit id in, ipsa quae reiciendis repellendus suscipit unde veniam voluptas";

  // when the toggle is active, show the truncated text
  // if not, show the text in full. 
  return (
    <div className="App">
      <button onClick={() => setShowTruncate(!showTruncate)}>Show more</button>
      <p>{showTruncate ? truncate(content) : content}</p>
    </div>
  );
}
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