1

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

2 Answers 2

2

You could implement e.g. a counter variable and use Array#slice to show specified amount of elements inside the test array.

Codesandbox link

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.

Improved codesandbox link

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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> )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.