'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.)
Solution 1:[1]
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>
</>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
