1

I got this code where I'm parsing dynamic text into separate lines and rendering individual components for each line of text.

I'm using the map function to create an array for the elements and React demands a unique key for each element on the list.

I know usually it's not ideal to use index as the key. But in this case, what else can I do?

QUESTION

Can I use index as the key for the elements in this case without having issues? What could go wrong?

Note1: I cannot use the values as the keys, because all lines might have the exact same values, hence they wouldn't be unique.

Note2: This code runs inside an Admin form for BlogPosts. I write some custom markup text, just like in the textarea for questions on StackOverflow and I need to parse it to give it proper styles when rendered out on the screen as a blog post. Like: **bold text**, etc. And each line should be rendered as a different paragraph.

UPDATE:

I've read the article you all mentioned in comments and answer. And here's what the author points out:


enter image description here

Does my case meet all 3 requirements?

1 - Do they change? In theory they do.

2 - They have no ids.

3 - They are not filtered for sure. But are they reordered? What if you copy "line1\nline2\nline3" paste into Notepad and change it to "line3\nline2\nline1" and paste it back into the textarea. Does it count as re-ordering? I just tested it and it renders just fine.

Anyway, so far I haven't run into any issues and it feels safe to use. But I would like an in-depth explanation of how it works in this case.


function App() {
  const [inputValue,setInputValue] = React.useState("line1\nline2\nline3");
  const lineItems = inputValue.split("\n").map((line,index) => 
    <TextLine 
      key={index}
      index={index}
      value={line}
    />
  );
  
  return(
    <React.Fragment>
      <textarea 
        onChange={()=>setInputValue(event.target.value)} 
        value={inputValue}
        style={{width: "300px", height: "60px"}}
      />
      {lineItems}
    </React.Fragment>
  );
}

function TextLine(props) {
  return(
    <div>{props.value + " (key = " + props.index + ")"}</div>
  );
}

ReactDOM.render(<App/>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>
cbdeveloper
  • 27,898
  • 37
  • 155
  • 336
  • I think that using index is not considered wrong but to be extra sure you can use UUID. This is just a precaution, not a deaddrop requirement. – vinayak shahdeo Jan 03 '20 at 09:27
  • here you can find a good article on when it's not a very good idea to use index as key. https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318 – Ayyappa Gollu Jan 03 '20 at 09:31
  • as long as you don't rearrange or filter the array, it's safe. – hotpink Jan 03 '20 at 09:31
  • Yes, U can. Someone can say that u can't do that, it's kinda antipattern, but u can and in my opinion, it's no so bad. Even u can generate keys like key={"text-line${index}"}, if u want to make them unique – Diyaz Yakubov Jan 03 '20 at 09:32
  • here is the answer that explains how should you use it: https://stackoverflow.com/a/46735689/6818430 – Navin Gelot Jan 03 '20 at 09:43
  • @NavinGelot that not exactly my case. Try to select the full `line1` from my snippet and delete. You'll see that it renders just fine. React won't think you've deleted the last line, like the answer you're mentioning. Somehow it's a different situation from mine, but I can't put it in words the difference. – cbdeveloper Jan 03 '20 at 09:49

1 Answers1

4

Note: Don't use the index if the items have a unique id (and a non-primitives list should), because it's an anti-pattern as per documentation

When you don't have a unique id for the items, you can use the index.

const Numbers = ['One', 'Two', 'Three', 'Four'];

const App = () => (
  <ul>
  {Numbers.map (
    (number, index) => <li key={index}>{number}</li>
  )}
  </ul>
)

Without a unique key, React couldn’t differentiate if the element was removed or just the content is changed.

Solutions for unique key...

1- You can create a function to generate unique keys/ids/numbers/strings and use that

2- You can use npm packages(library) like uuid, uniqid, shortid...

3- I recommend using the unique ID you get from the database, If you get it.

akhtarvahid
  • 9,445
  • 2
  • 26
  • 29