Apologies. Newbie here having problems with passing a JSON object into a function as props. I'm obviously doing something wrong but I've searched and other people's posts seem more complex than mine.
I want to pass an array which may have zero or more rows into a function and then I want to count how many rows there are. Finally I would return a string depending on that. I've got the last part working but I can't pass the array without getting undefined.
App.js
const sampleTeams = [
{
team: "Jets",
season: "2022/23",
regfee: 35,
feepaid: true,
},
];
function App() {
return (
<Container className="my-4">
<MemberCard
forename="Bob"
surname="Jones"
playerNumber="154"
registrations={sampleTeams}
></MemberCard>
</Container>
);
}
MemberCard.js
export default function MemberCard({
forename,
surname,
memberNumber,
registrations,
}) {
return (
<Card>
<Card.Body>
<Card.Title className="d-flex justify-content-between slign-items-baseline fw-normal mb-3">
<div className="me-2">
{forename} {surname}
</div>
<div className="d-flex align-items-baseline text-muted fs-6 ms-1">
{memberNumber}
</div>
</Card.Title>
<p>{getNumberOfTeams({ registrations })} registered</p>
<Stack direction="horizontal" gap="2" className="mt-4">
<Button variant="outline-primary" className="ms-auto">
Register Team
</Button>
</Stack>
</Card.Body>
</Card>
);
}
function getNumberOfTeams(registrations) {
const numberOfTeams = registrations.length;
// console.log(numberOfTeams);
if (numberOfTeams === 1) return "1 team";
return numberOfTeams " teams";
}
CodePudding user response:
In your example code, there is the object shorthand in the argument of the call to getNumberOfTeams
getNumberOfTeams({ registrations })
The function getNumberOfTeams(registrations)
attempts to read registrations.length
, but you passed it an object { registrations: registrations }
. Object.length
will always be undefined
. Your code should work more correctly if you change it to
<p>{getNumberOfTeams(registrations)} registered</p>