I have an array of objects. How can I loop through this array on click?
test = ['a', 'b', 'c', 'd']
{this.state.test.map(function(i){
return <span> {i} </span>
})}
I would normally loop through like this in react but this prints them all out at once. How can I display 'a' on the page and then the next time i click it, I display 'b' so on until the end of the array?
I need a function that can tell where I am in the array and display that on the page at the right moment
You could implement eg a counter variable and use Array#slice
to show specified amount of elements inside the test
array.
import React from "react";
export default class Hello extends React.Component {
state = {
test: ["a", "b", "c", "d"],
index: 0
};
handleClick = () => {
let i = this.state.index < this.state.test.length ? this.state.index += 1 : 0;
this.setState({ index: i });
};
render() {
return (
<div>
{this.state.test.slice(0, this.state.index).map(v => {
return (
<span>{v}</span>
);
})}
<button onClick={this.handleClick}>Click</button>
</div>
);
}
}
Edit : I was playing with it and actually I got even a better solution, which allows you to avoid re-looping Array#map
on every render, with little help of hidden
attribute. Also we are getting rid of the Array#slice
function.
app.js
{this.state.test.map((v, i) => {
return (
<span hidden={i >= this.state.index}>{v}</span>
);
})}
And the Span.js
component:
<span hidden={this.props.hidden}>
{this.props.v}
</span>
set initial index at your state first, then use that index as index array in span. next make some function to handle the increment, simply put it like this
const switchNinjaHandler = () => {
let looper = ++this.state.index % this.state.test.length;
setState({
...personsState, // WE SHOULD ALWAYS GIVE THE EXCACT INITIAL STATE VALUE, THIS IS WHERE SPREAD COMING HANDY
this.index : looper,
});
to display
return ( <div> {this.state.test[this.index]} </div> )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.