Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make key unique in nested map

{'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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

012 3456 78 91011 121314151617

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading