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

79
Visualizações
How to return a string from an array using React.js useState hook

I'm using the useState hook in React and am trying to return a string to display in an h1 element from an array every time I click a button to call a function.

I tried using a for loop to return the index of each array, however, my h1 element only displays the last index of the array. Here is my code:

import React, { useState } from "react";

export default function App() {
  const [state, setState] = useState("Start");

  const greeting = ["Hello", "World!"];

  function nextWord() {
    for (let i = 0; i < greeting.length; i++) {
      setState(greeting[i]);
    }
  }

  return (
    <>
      <h1>{state}</h1>
      <button onClick={nextWord}>+</button>
    </>
  );
}

As you can see, my nextWord function only displays the last item of my array on the h1 element. How do I get it to display index 0, index 1, etc... with each click of the button calling the nextWord function. (E.g., It will display "Hello" in the h1 the first click, and then "World" on the next click.)

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

0

One way would be to store the index instead of the actual word.

import React, { useState } from "react";

export default function App() {
  const [state, setState] = useState(0);

  const greeting = ["Start", "Hello", "World!"];

  function nextWord() {
    setState((state + 1) % greeting.length)
  }

  return (
    <>
      <h1>{greeting[state]}</h1>
      <button onClick={nextWord}>+</button>
    </>
  );
}

Your state variable(s) could have a more descriptive name, in this case you could name them wordIndex and setWordIndex.

If you only need the "Start" to display in the beginning (so that "Start" does not repat) then you can change the logic slightly.

import React, { useState } from "react";

export default function App() {
  const [state, setState] = useState(-1);

  const greeting = ["Hello", "World!"];

  function nextWord() {
    setState((state + 1) % greeting.length)
  }

  return (
    <>
      <h1>{greeting[state] || "Start"}</h1>
      <button onClick={nextWord}>+</button>
    </>
  );
}
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