0

I am rendering some components using array map function, and I'm getting "Each child in an array or iterator should have a unique "key" prop." warning. I know that I do have to assign key props to the array rendered components.

My question is, do I have to just assign key to the most outer component (this case View) that is inside the map function, or do I have to assign key to every element inside the outer most component view?

If latter is the case, then assigning key to every component is a little inefficient I think? Is there any way to solve this problem? Thank you

this.state.Store.City.map((item) => {
        return <View>
          <TouchableOpacity onPress={() => this.onQueryInputChange(item)}>
            <Text style={{ fontSize: 20, paddingVertical: 10 }}>
              {item.fullName}
            </Text>
          </TouchableOpacity>
        </View>
      })
1
  • 1
    The outer most element needs key. In your case add key prop to View. and not required for other elements Commented Sep 6, 2018 at 2:43

2 Answers 2

1

If you don't have an id in item, you can use the item array index if the list will not be reordered or reorganized :

this.state.Store.City.map((item, index) => {
   return (
     <View key={index}>
      <TouchableOpacity onPress={() => this.onQueryInputChange(item)}>
        <Text style={{ fontSize: 20, paddingVertical: 10 }}>
          {item.fullName}
        </Text>
      </TouchableOpacity>
     </View>
   );
})

Only the outermost component needs a key to keep track of each item.

Sign up to request clarification or add additional context in comments.

Comments

1

You should assign a key to the most outter component (here it would be View component) here is the documentation

if item has an ìd property you could write

this.state.Store.City.map((item) => {
   return (
     <View key={item.id}>
      <TouchableOpacity onPress={() => this.onQueryInputChange(item)}>
        <Text style={{ fontSize: 20, paddingVertical: 10 }}>
          {item.fullName}
        </Text>
      </TouchableOpacity>
     </View>
   );
})

1 Comment

Thank you for the answer! I got it solved really appreciate it!

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.