Home > Mobile >  Passing string from parent to render multiple children
Passing string from parent to render multiple children

Time:10-12

I may lose something on the way.. I want to pass object arguments to a children to dinamically render it in three different ways.

Here is my object:

const cards = [
        {
            imgSrc: "first",
            desc: "some text"
        },
        {
            imgSrc: "second",
            desc: "some text"
        },
        {
            imgSrc: "third",
            desc: "some text"
        }
    ];

This is the children component:

import { Box } from '@mui/system'
import React from 'react'

import "../../style/main.scss"

import first from "../../images/veloce.png"
import second from "../../images/sicuro.png"
import third from "../../images/vicino.png"
import { Typography } from '@mui/material'

function Card( source, text ) {
    return (
        <Box className="foundation-card">
            <img src={source}/>
            <Typography variant="h6">{text}</Typography>
            <Typography variant="body2">{text}</Typography>
        </Box>
    )
}

export default Card

And then i have the parent component where i want to render multiple Card mapping the cards array:

import Card from "./Card"
import CustomDivider from "../foundation/CustomDivider"

function Values() {

    return (
        <Box className="vertical-box main-maxw section-margin">
            <Typography variant="h4">Perchè sceglierci</Typography>
            <CustomDivider />
            <Box className="foundation-box values">
                {cards.map((p) => {
                    return <Card source={p.imgSrc} text={p.desc} />
                })}
            </Box>
        </Box>
    )
}

export default Values

and then i receive this:

Error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.

I suppose it is a stupid error but i am in my first approach and i don't know how to move. Thank you all.

CodePudding user response:

I think the problem is that your card function is expecting positional arguments but you're calling it with an object.

<Card source={p.imgSrc} text={p.desc} />
// These two things are equivalent.
Card({source: p.imgSrc, text: p.desc})

So essentially you were assigning the source arg and object that contained both source and text.

Try changing your card function to accept an object

function Card({source, text}) {
...
}

CodePudding user response:

I see some strange things.

1- where you are mapping the cards, you are not importing the cards array, or i cant see where are you getting the cards array from

2- function card is a react component so you should wrap the props with {} as this: function Card({source,text})

  • Related