I have a parent component that use a map to render child components with some data. I need to pass the data as props to the child component but when i pass them i cant access them in child component. this.props.children prop has the props i need but is there a better way to pass them to the child component?
Parent component
class Home extends Component {
renderArtCards = (artCardArray) => {
return (artCardArray.map((artCard, index) => {
return (
<div key={index}>
<ArtCard>
title={artCard.title}
image={artCard.image}
description={artCard.description}
price={artCard.price}
</ArtCard>
</div>
)
})
)
}
render() {
return (
<Fragment>
<div className="row no-gutters justify-content-end pageTitleRow">
<div className="pageTitle">Home</div>
</div>
<div className="artCardsRow">
<Masonry
className={'masonryStyle'}
options={masonryOptions}>
{this.renderArtCards(artCards)}
</Masonry>
</div>
</Fragment>
)
}
}
Child component
class ArtCard extends Component {
render() {
console.log(this.props.children)
return (
<Fragment>
<Card className="artCardBody">
<CardMedia
className="artCardMedia"
image={this.props.image}
title={this.props.title}
/>
<CardContent>
<div className="row artCardTitleRow">
<div className="artCardTitle">{this.props.title}</div>
<div className="artCardPrice">Rs.{this.props.price}</div>
</div>
<div className="text-muted">{this.props.description}</div>
</CardContent>
</Card>
</Fragment>
)
}
}
I need to access props in child component with this.props.xxxx
The props go inside the <Name ... >
. You currently pass no props to <ArtCard>
, just text as its children.
You dont need a class
for your child component so let do this (dumb component):
const ArtCard = ({ image, title, price, description }) => ( return ( <Fragment> <Card className="artCardBody"> <CardMedia className="artCardMedia" image={image} title={title} /> <CardContent> <div className="row artCardTitleRow"> <div className="artCardTitle">{title}</div> <div className="artCardPrice">Rs.{price}</div> </div> <div className="text-muted">{description}</div> </CardContent> </Card> </Fragment> ) } )
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.