Home > Net >  How do I pass JSON with objects in objects to a component [REACT]
How do I pass JSON with objects in objects to a component [REACT]

Time:09-22

I am new to REACT and want to do a challenge with (different) stories thats displays the stories in different cards.

So I tried to create a card component that displays title, description and difficulty. I added an object named stories

class Card extends React.Component {
render() {
    const stories = [
        {
            id: 1,
            title: 'First black story',
            desc: 'Can you solve this hard puzzle?',
            grade: 'Hard'
        },
        {
            id: 2,
            title: 'Second black story',
            desc: 'This should be easy for you!',
            grade: 'Makkelijk'
        }
    ];

I tried mapping through to object and adding all the details do elements like <h2>, <p> with map function:

return({stories,map((story, index) => {
        return (
          <div key={index}>
            <h2>name: {story.title}</h2>
            <h2>country: {story.desc}</h2>

            <hr />
          </div>
        );
      })});
}

}

export default Card;

and tried to call the cards in my Home.js with

<div id="cardsOverview">
   <Card />
   <Card />
   <Card />
</div>

But without success, what am I doing wrong? I personally think the <Card /> is not going to work that easily because REACT doesn't know what card it should load, but I want it to load every card, so why should it matter WHAT card.

CodePudding user response:

I have a few remarks. first of all, your list of cards are defined within the card object. This seems to be not logical. You want your list of cards to be defined at a higher level, and then map over this list, generating a <Card /> for each item of your list.

If you got your setup to work as it is now (a few more syntax issues, like cards not returning everything in one tag, curly braces around your return), you would generate 3 card components, and each card creates the 3 stories, giving you 9 cards on the page.

<div id="cardsOverview">
    {
        stories.map((story, index) => <Card key={index} story={story} /> );
    }
</div>

Your card should then be able to use those props to draw a single card:

class Card extends React.Component {
    render() {
     return (
         <div key={this.props.key}>
            <h2>name: {this.props.story.title}</h2>
            <h2>country: {this.props.story.desc}</h2>
            <hr />
         </div>
     )
}

Have a look at this, and see if you get it to work.

  • Related