Home > front end >  Passing down an array of Objects as props for a React Component
Passing down an array of Objects as props for a React Component

Time:02-10

I want to pass down an array of Objects to a child component. Each child component should return the value of the respective index of dummyData.

Parent Component

export default function MainContent() {
  const dummyData = [
    {
      id: "1",
      cardIMG: "test.png",
      cardTitle: "Title",
      cardText: "Text"
    },
    {
      id: "2",
      cardIMG: "test1.png",
      cardTitle: "Title",
      cardText: "Text"
    }
  ];

  return (
    <div className="MainContainer">
      <Card props={dummyData} />
      <Card props={dummyData} />
    </div>
  );
}

Child Component

export default function Card(props) {
  return (
    <div className="CardContainer">
      <div className="CardIMG">
        <img src={this.props.CardIMG} alt="" />
      </div>

      <div className="TextContent">
        <h2>{this.props.CardTitle}</h2>
        <p className="TextBlock">{this.props.CardText}</p>
        <button className="ReadMore">Read more</button>
      </div>
    </div>
  );
}

CodePudding user response:

Since you are trying to iterate through an array, you have to loop through the items. You can use for, map or each, totally upto you.

Refer loops: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration

You can basically do this in your parent component:

export default function MainContent() {
  const dummyData = [
    {
      id: "1",
      cardIMG: "test.png",
      cardTitle: "Title",
      cardText: "Text"
    },
    {
      id: "2",
      cardIMG: "test1.png",
      cardTitle: "Title",
      cardText: "Text"
    }
  ];

  return (
    <div className="MainContainer">
      {dummyData.map((data) => {
        <Card key={data.id} cardInfo={data} />
      })
    </div>
  );
}

And in your child component(which is a functional component, so you can't use this in there), you can do

export default function Card(props) {
  return (
    <div className="CardContainer">
      <div className="CardIMG">
        <img src={props.cardInfo.cardIMG} alt="" />
      </div>

      <div className="TextContent">
        <h2>{props.cardInfo.CardTitle}</h2>
        <p className="TextBlock">{props.cardInfo.CardText}</p>
        <button className="ReadMore">Read more</button>
      </div>
    </div>
  );
}
  •  Tags:  
  • Related