lundi 6 août 2018

Defining React Prop Keys When Calling Static Child Components

I'm trying to better understand the role of keys in React components. I've read quite a bit but every example I've seen (like the one in the React docs or the great explanation on S.O.) assumes the data coming into the component is dynamic.

The examples all apply keys with array index values or using something like .map() to assign database IDs dynamically to each instance of the child component, and satisfy React's need for keys.

My example is on a static site with static content coming into the child component that gets called a couple of times. Best I figured, I could create a random number generator function getRandomInt and apply the key that way.

Unfortunately this results in the familiar React error:

Each child in an array or iterator should have a unique "key" prop. Check the render method of CaseStudyOpinionSummary. It was passed a child from DiagnosticCaseStudy.

Where am I going wrong?

import React from 'react'
import CaseStudyOpinionSummary from '../../../components/CaseStudyOpinionSummary'

export default class DiagnosticCaseStudy extends React.Component {

  getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min
  }

  render() {
    return (
      <CaseStudyOpinionSummary
        part="Part One"
        partTitle="Diagnosis"
        partSubtitle="Primary Care Encounter"
        partSummary="Short brief"
        key={ this.getRandomInt(0, 100000) } 
      />
      <CaseStudyOpinionSummary
        part="Part Two"
        partTitle="Medication and Management"
        partSubtitle="Initial Gastroenterologist Encounter"
        partSummary="Another short brief"
        key={ this.getRandomInt(0, 100000) } 
      />
    )
  }




Aucun commentaire:

Enregistrer un commentaire