Gemada
Gemada

Reputation: 21

Array.map item to a state

How do I get the values of array.map outside of it?

For example:

array.map(index, item) => { return ( <Text>{item.ID}</Text> ) }

Ouside of it I have something like:

<Button onPress={() => this.editItem(CURRENT_ITEM_ID)}></Button>

Where CURRENT_ITEM_ID is the current item on a Card, for example.

Like Tinder I have an array of Cards to Swipe, that I'm mapping, but the Like button is not part of the Card. This way I'm not moving the Like button with the Card, instead it is static, I'm just moving the content of the card. So I need a way to access the current item from outside of the map. The Card has Text and ID. The component below have a Button that I need to click passing the item.ID of the current Card.

Is there a way to set this item to a state?

Thank you.

Upvotes: 0

Views: 1373

Answers (2)

Stephen L
Stephen L

Reputation: 2339

One solution is to create a state property that holds the id of the card that is showing, and then when the button is clicked, you grab that state and do something with it. Here is an example with onClicks and divs.

const arr = ['card1', 'card2', 'card3', 'card4'];

class App extends React.Component {
  constructor(props) {
    super(props)
    this.handleClick = this.handleClick.bind(this);
    this.handleButtonClick = this.handleButtonClick.bind(this);
  }
  handleClick(index) {
    this.setState({ visibleCard: index });
  }
  handleButtonClick() {
    console.log('this.state.visibleCard', this.state.visibleCard);
    console.log('visibleCard', arr[this.state.visibleCard]);
  }
  render() {
    return (
      <div>
        {arr.map((card, i) => <div onClick={() => this.handleClick(i)}>{card}</div>)}
        <button onClick={this.handleButtonClick}>test</button>
      </div>
    )
  }
}

The basic idea is that you tie the index to the card. A handler then sets that state to visible(not sure what this would be in your case since it seems like a mobile app). Then in your button, you use the state to grab the visible card and pass the data to whatever other function you need.

Upvotes: 1

Chase DeAnda
Chase DeAnda

Reputation: 16441

What I normally do is bind the event in the map function.

array.map( (item, key) => {
    return (
        <div>
            <Text>{item.ID}</Text>
            <button onClick={this.editItem.bind(this, item.ID)}>Edit</button> 
        </div>
    )
}

Not sure what your HTML looks like, but you need to bind the function params in the map.

Upvotes: 0

Related Questions