How to render JSON data in react

How to render JSON data category wise in react

Json Data
{
  "Category One": [
      {"link_id": 3, "Link": "a.com", "Title": "A TITLE"},
      {"link_id": 4, "Link": "b.com", "Title": "B TITLE"},
      {"link_id": 5, "Link": "c.com", "Title": "C TITLE"}
  ],
  "Category Two": [
      {"link_id": 6, "Link": "d.com", "Title": "D TITLE"},
      {"link_id": 7, "Link": "e.com", "Title": "E TITLE"}
  ]
}

Example

import React from 'react';

const MyComponent = () => {
    const data = {
        "Category One": [
            {"link_id": 3, "Link": "a.com", "Title": "A TITLE"},
            {"link_id": 4, "Link": "b.com", "Title": "B TITLE"},
            {"link_id": 5, "Link": "c.com", "Title": "C TITLE"}
        ],
        "Category Two": [
            {"link_id": 6, "Link": "d.com", "Title": "D TITLE"},
            {"link_id": 7, "Link": "e.com", "Title": "E TITLE"}
        ]
    };

    return (
        <div>
            <h1>Render JSON Data by Category</h1>
            {Object.keys(data).map((category, index) => (
                <div key={index}>
                    <h2>{category}</h2>
                    <ul>
                        {data[category].map((item) => (
                            <li key={item.link_id}>
                                <strong>{item.Title}</strong>: <a href={item.Link}>{item.Link}</a>
                            </li>
                        ))}
                    </ul>
                </div>
            ))}
        </div>
    );
};

export default MyComponent;

Output

Explanation

The data variable is a JavaScript object representing the JSON structure with categories as keys and arrays of links as values.

Rendering Categories:

For iterate category Object.keys(data).map() is used (eg: “Category One” and “Category Two”).

Rendering Links:

data[category].map() function is used for iterates over the array of items (links) for each category

Each item is rendered as a list item (<li>)

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *