Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Each child in a list should have a unique "key" prop

I have a const defined with multiple functions that are irrevelant to the question, so am just including a sanitized segment that's relevant. Let me know if I should include anything more.

      return (
        <React.Fragment key={index}>
          <hr className={hrClasses} />
          <span className={spanClasses}>
            {isTrue ? 'x' : index + 1}
          </span>
        </React.Fragment>
      );
    })}
  </div>
);

In the browser, I see the warning:

Warning: Each child in a list should have a unique "key" prop.

Since the hr element doesn't need a unique key prop, how can I get around this error?

I've tried different variations of keys, such as adding key={index} to the hr element and re-labelling the index key as id for the span. I'm not sure what else to try. Any guidance would be much appreciated!

like image 359
IAspireToBeGladOS Avatar asked Mar 31 '19 01:03

IAspireToBeGladOS


1 Answers

You are not applying the key to the parent Fragment.

You can use <> the same way you’d use any other element except that it doesn’t support keys or attributes. ~ https://reactjs.org/docs/fragments.html#short-syntax

You are using the short syntax of <> which does not support keys. Use:

<React.Fragment key={index}>
      <hr className={styles.hr} />
      <span className={styles.span}>
        {isValidated ? 'x' : index + 1}
      </span>
 <React.Fragment/>
like image 112
JavanPoirier Avatar answered Sep 21 '22 14:09

JavanPoirier