Home > Software design >  How to reference image in an array?
How to reference image in an array?

Time:04-30

I have some data im using in an array that looks like:

import image from "./image.jpg";
export const data = [
  {
    id: 1,
    title: "kevin",
    content: `Guy`,
    image: {image},
    contact: "123-1234-1234",
  },
]

Which is mapped to a component to render the data:

<Grid container spacing={4}>
        {data.map((item, idx) => (
          <Grid item key={idx} xs={12} sm={6} md={4}>
            <Card
              sx={{ height: "100%", display: "flex", flexDirection: "column" }}
            >
              <CardMedia
                component="img"
                sx={{
                  // 16:9
                  pt: "5.25%",
                }}
                image={item.image}
                alt="random"
              />
              <CardContent sx={{ flexGrow: 1 }}>
                <Typography gutterBottom variant="h5" component="h2">
                  {item.title}
                </Typography>
                <Typography>{item.content}</Typography>
              </CardContent>
              <CardActions>
                {item.Contact ? <Button size="small">Contact</Button> : null}
              </CardActions>
            </Card>
          </Grid>
        ))}
      </Grid>
    </Container>

How would I go about rendering the image given that its being passed as an attribute

CodePudding user response:

You're using image: {image} - that's giving this output (other properties stripped):

data = [{
    image: {
        image: image
    }
}]

If you want to export image's value with image as the key, you can just set the key to be equal to the variable as a value (the simplest method):

image: image

Or you can use property value inference for something a bit neater:

content: `Guy`,
image,

Full code:

export const data = [{
    id: 1,
    title: "kevin",
    content: "Guy",
    image,
    contact: "123-1234-1234"
}];

CodePudding user response:

You are not passing the image to the image key in your object but a new object with another image key in it. Try this instead:

import image from "./image.jpg";
export const data = [
  {
    id: 1,
    title: "kevin",
    content: `Guy`,
    image: image,
    contact: "123-1234-1234",
  },
]
  • Related