Reputation: 31
I am trying to fetch data from a JSON file using map function, but I keep getting this error 'Each child in a list should have a unique "key" prop' even though I set the key={facts.id}. Please how can I get rid of this error? Every other thing is working fine.
import React from "react";
import ResponsiveAppBar from "./ResponsiveAppBar";
import Typography from "@mui/material/Typography";
import { styled } from "@mui/material/styles";
import Box from "@mui/material/Box";
import Paper from "@mui/material/Paper";
import Grid from "@mui/material/Grid";
import Facts from "../sources/facts.json";
import Data from "../sources/credits.json";
const Learn = () => {
const Item = styled(Paper)(({ theme }) => ({
backgroundColor: theme.palette.mode === "dark" ? "#1A2027" : "#fff",
...theme.typography.body2,
padding: theme.spacing(2),
textAlign: "center",
color: theme.palette.text.secondary,
}));
return (
<div>
<ResponsiveAppBar />
{Facts &&
Facts.map((fact) => {
return (
<Box sx={{ flexGrow: 1 }} style={{
marginTop:50}}>
<Grid
container
spacing={2}
elevation={9}
justifyContent="center"
style={{ margin: "auto" }}
>
<Grid item xs={8} >
<Item key={fact.id} >
<Typography
variant="h5"
gutterBottom
component="div"
style={{ fontWeight: 600 }}
>
{fact.id}. {fact.title}
</Typography>
<Typography variant="body1" gutterBottom>
{fact.content}
</Typography>
</Item>
</Grid>
</Grid>
<br />
<br />
</Box>
);
})}
</div>
);
};
export default Learn;
Upvotes: 0
Views: 2410
Reputation: 31
I got it working by adding an index to the map function parameter, and setting the key to equal the index.
Facts.map((fact, i) => {
return (
<Box sx={{ flexGrow: 1 }} style={{
marginTop:50} key={i}>
Upvotes: 0
Reputation: 2433
You should assign key
to the first element you return :
return (
<Box key={fact.id} sx={{ flexGrow: 1 }} style={{
marginTop:50}}>
Upvotes: 1