Home > Mobile >  Looping through JSON objects and converting them to React components
Looping through JSON objects and converting them to React components

Time:12-11

I have a JSON file with 3 different objects inside of them (card1, card2 and card3). I want to loop through these objects in JavaScript, turn them into an array of objects, then in my React code, I'm trying to turn them into Components depending on how many there are in the JSON file.

What I have so far:

import Card from "./card-elements/Card";
import json from "./data.json";

const list = [];
for (const key in json) {
    if (json.hasOwnProperty(key)) {
        list.push(key);
    }
}

function App() {
    return (
        <div className="card-area">
            {list.map(i => {
                return <Card title={i.title}
                             description={i.description}
                             borderColor={"red"}/>
            })}
        </div>
    );
}

export default App;

data.json:

{
    "card1": {
      "title": "Card One",
      "description": "This is card one's description. Straight from JSON file!"
    },
    "card2": {
      "title": "Card Two",
      "description": "Directly from the JSON file, this is card two's description"
    },
    "card3": {
      "title": "Card Three",
      "description": "And finally, this is the last cards description!"
    }
}

Current output: No errors occur with my React, it just only displays one Component and the "title" and "description" are not showing

Any help would be appreciated, thank you!

CodePudding user response:

No need to push each item to a list and use it. Instead of use Object.entries.

Try like this


function App() {
    return (
        <div className="card-area">
            {(Object.entries(json) || []).map(([key, value]) => {
                return (
                    <Card
                        title={value.title}
                        description={value.description}
                        borderColor={"red"}
                    />
                );
            })}
        </div>
    );
}

CodePudding user response:

In React, you should to use the useState hook to update a component.

Try something like:

import Card from "./card-elements/Card";
import json from "./data.json";


function App() {
    const [cardData, setCardData] = React.useState();

    React.useEffect(() => {
      const list = [];
      for (const key in json) {
       if (json.hasOwnProperty(key)) {
          list.push(key);
       }
      }
    }, [])

    return (
        <div className="card-area">
            {cardData && list.map(i => {
                return <Card title={i.title}
                             description={i.description}
                             borderColor={"red"}/>
            })}
        </div>
    );
}

export default App;

  • Related