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

183
Visualizações
Create objects using last part of a string?

I am creating a react app that takes text input and outputs it in 280 character (tweet-sized) objects, essentially splitting it into one big Twitter thread.

I can't figure out how to split them up into these 280-character objects and keep updating the list of objects (tweets) as I type into the text box?!

Any help would be appreciated.

const [content, setContent] = useState("");
const [tweets, setTweets] = useState([
    { text: "First tweet.", id: 1 },
]);
let remainder = content.length - ~~(content.length / 10) * 10;
  let prevTweetsLength = content.length - remainder;

  const contentHandler = (e) => {
    setContent(e.target.value);
    tweetHandler(content);
    console.log(content);
  };

  const tweetHandler = (c) => {
    tweets[prevTweetsLength / 10] = {
      text: c,
      id: tweets.length + 1,
    };
    if (remainder === 1) {
      setTweets([
        ...tweets,
        {
          text: c.substring((prevTweetsLength)),
          id: Math.random() * 1000,
        },
      ]);
    }
  };```
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

First, we can define a function which will split a text into tweets, using slice(start, end) which returns the content between the start position and end position.

function splitIntoTweets(content, tweetLength = 280) {
  const nTweets = content.length / tweetLength;

  const tweets = [];
  for (let i = 0; i < nTweets; i++) {
    tweets.push({
      text: content.slice(i * tweetLength, (i + 1) * tweetLength),
      id: i,
    });
  }
  return tweets;
}

Then, inside your components, you could do:

const [content, setContent] = useState("");
const [tweets, setTweets] = useState([]);

// Every time content changes, we update the list of tweets.
useEffect(() => {
  setTweets(splitIntoTweets(content));
}, [content])

// Rest of your code ...
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