0

I have 4 different divs each containing their own button. When clicking on a button the div calls a function and currently sets the state to show a modal. Problem I am running into is passing in the index of the button clicked.

In the code below I need to be able to say "image0" or "image1" depending on the index of the button I am clicking

JS:

handleSort(value) {
  console.log(value);
  this.setState(prevState => ({ childVisible: !prevState.childVisible }));
}


const Features = Array(4).fill("").map((a, p) => {
 return ( 
    <button key={ p } onClick={ () => this.handleSort(p) }></button>
  )
});



{ posts.map(({ node: post }) => (
this.state.childVisible ? <Modal key={ post.id } data={ post.frontmatter.main.image1.image } /> : null
    ))

}

user992731
  • 3,400
  • 9
  • 53
  • 83

1 Answers1

1

I would suggest:

  1. saving the button index into state and then
  2. using a dynamic key (e.g. object['dynamic' + 'key']) to pick the correct key out of post.frontmatter.main.image1.image

-

class TheButtons extends React.Component {
  handleSort(value) {
    this.setState({selectedIndex: value, /* add your other state here too! */});
  }

  render() {
    return (
      <div className="root">
        <div className="buttons">
          Array(4).fill("").map((_, i) => <button key={i} onClick={() => handleSort(i)} />)
        </div>
        <div>
          posts.map(({ node: post }) => (this.state.childVisible
            ? <Modal
                key={ post.id }
                data={ post.frontmatter.main.[`image${this.state.selectedIndex}`].image }
              /> 
            : null
          ))
        </div>
      </div>
    );
  }
}

This is a good answer which explains "Dynamically access object property using variable": https://stackoverflow.com/a/4244912/5776910

Rico Kahler
  • 17,616
  • 11
  • 59
  • 85