bleepmeh
bleepmeh

Reputation: 1037

How to keep track of a group of mapped components in React Native?

I have a group of text buttons that are rendered by mapping data:

  <View style={{paddingTop: '3%', height:"100%", width:1400, flexDirection: "row", flexWrap: 'wrap'}}>
    {this.props.data.map((item, index) => {
      console.log("profession item: ", item)
      return (
        <View 
          style={{margin:4, marginHorizontal:12}}
          key={item.pro_id}>
          <TextItemToggle
            value={item.en}
            onPress={(value)=>{this._onPressHandler(value)}}
          />
        </View>
      )
    })}
  </View>

Only one of the button can be highlighted. Once another button is pressed and highlighted, the one that is already highlighted will be toggled. I'm not sure how to keep track of components rendered through mapping.

I first thought of using string (each button has a unique string value) to reference each button, but it is likely to be deprecated according to https://hashnode.com/post/why-are-string-refs-considered-legacy-in-react-cit1ttd8x0spevx53ltk1gdhh Are there any other approaches?

Upvotes: 0

Views: 114

Answers (1)

bennygenel
bennygenel

Reputation: 24680

One option can be to store the id of the item that needs to be highlighted in state and while mapping checking that id to highlight.

Example

_onPressHandler = (event, id) => {
  this.setState({ selected: id});
}

render() {
  return (
    <View style={{paddingTop: '3%', height:"100%", width:1400, flexDirection: "row", flexWrap: 'wrap'}}>
      {this.props.data.map((item, index) => {
        console.log("profession item: ", item)
        return (
          <View 
          style={[{margin:4, marginHorizontal:12}, (this.state.selected === item.pro_id : {backgroundColor: 'grey'} : {})]}
          key={item.pro_id}>
            <TextItemToggle
            value={item.en}
            onPress={(value)=>{this._onPressHandler(value, item.pro_id)}}
            />
          </View>
        )
      })}
    </View>
  )
}

Upvotes: 1

Related Questions