Home > other >  How to make key unique in nested map
How to make key unique in nested map

Time:10-23

{'The Lord of the Rings'.split(' ').map((word, wordIndex) => (
  <View key={wordIndex}>
    {word.split('').map((letter, letterIndex) => (
      <Button key={letterIndex}>
        <Text>       
          {letterIndex}
        </Text>
      </Button>
    ))}
  </View>
))}

The output of this code:

012 0123 01 012 01234

How can I achieve this in ever increasing unique key pattern?

012 3456 78 91011 121314151617

CodePudding user response:

One possibility is to use the third argument in the first .map() (see arr below), calculate the length of all previous words (arr.slice(0, wordIndex).join('').length) and add that to letterIndex. See demo:

function App() {
  return (
    <div>
      {'The Lord of the Rings'.split(' ').map((word, wordIndex, arr) => (
      <div key={wordIndex}>
        {word.split('').map((letter, letterIndex) => (
          <span key={letterIndex}>
            {arr.slice(0, wordIndex).join('').length   letterIndex}
          </span>
        ))}
      </div>
      ))}
    </div>
  )
}

ReactDOM.render(<App />, document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>

  • Related