1

Currently the below code renders just fine I get several TEXT components displaying text on the screen

I also get a warning though that says each child in a list should have a unique "key" prop

renderAlertItem = (alerts) => {
        arr = []
        for (var x = 0; x < alerts.length-1; x++){ //the last item in the list is the add alert button so we can ignore it
            arr.push(
            <Text style={{color: colors.whiteText}} >
                Settings for the {alerts[x].alertname} alert
            </Text>
            )
        }
        return arr
    }

    render() {
        const alerts=this.props.alerts

        return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center',}}>
            {this.renderAlertItem(alerts)}
        </View>
        );

    }

What's the best way to go about this?

doing this produces an error as the code is now returning a list of objects and not the list of <Text> components like it was before.

arr.push({key:x,item:
          <Text style={{color: colors.whiteText}} >
             Settings for the {alerts[x].alertname} alert
          </Text>
          })

NB: that this.props.alerts is an list of objects similar to this [{key:1, alertname:name, alerttype:type, setting:30}] and it already has its own key as part of the object. So could this be used somehow?

zoonosis
  • 799
  • 1
  • 11
  • 30
  • Possible duplicate of [Understanding unique keys for array children in React.js](https://stackoverflow.com/questions/28329382/understanding-unique-keys-for-array-children-in-react-js) – Julian W. Jul 25 '19 at 03:36

2 Answers2

1
renderAlertItem = (alerts) => {
        arr = []
        for (var x = 0; x < alerts.length-1; x++){ //the last item in the list is the add alert button so we can ignore it
            arr.push(
            <Text style={{color: colors.whiteText}} key={x}>
                Settings for the {alerts[x].alertname} alert
            </Text>
            )
        }
        return arr
    }
0

You should map your array to elements, and put the object key property right on the key prop of the element. Array::map creates a new array for you, and the slice(0, -1) gets all but the last array element. Here I have used object destructuring to extract the properties bring rendered, you can add alerttype later if needed.

renderAlertItem = alerts => alerts
  .slice(0,-1)
  .map(({ alertname, key }) => (
    <Text
      key={key}
      style={{color: colors.whiteText}}
    >
      Settings for the {alertname} alert
    </Text>
  ));
Drew Reese
  • 165,259
  • 14
  • 153
  • 181