Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

75
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda