Iterate a card component with properties from an array of objects

Split out your specific card component, use props for the dive school properties you’re going to pass in. You don’t have to do this, you can do it all inline, but for one thing the code gets very unwieldy if you don’t. So like:

const MyCard = ({ name, location }) => (
  <Card className={classes.root}>
    <CardHeader
      avatar={...avatar stuff}
      action={...action stuff}
      title={diveSchoolName}
      subheader= {diveSchoolLocation}
    />
    ...rest of the card stuff
  </Card>
);

Then something like:

<GridList
  className="team"
  key="Subheader"
  cellHeight={360}
  cols={3}
  spacing={2}
>
  { schoolList.map((school) => (
    <Grid item xs={6} sm={4}>
      <MyCard
        name={school.diveSchoolName}
        location={school.diveSchoolLovation}
      />
    </Grid>
  )}
</GridList>

You can’t use a loop, it’s not valid JS syntax – loops are statements, so you can’t have something in an object like:

{
  foo: for(let i = 0; i < 10; i++) {
    // Do something
  }
}

And that’s what you’re trying to do there in the commented out code. Whatever you use in the JSX code has to be an expression, because JSX is just a way of writing JS objects/functions using a syntax that looks like HTML. map is an expression, it just evaluates to a value, which in this case is an array of React components. map loops over an array of things (in this case objects), so each iteration of the loops lets you access the current item (which seems to be an object containing some information about dive schools).

1 Like