Daniel James
Daniel James

Reputation: 1

Mapping JSON - React

Can JSON be mapped via React in the format below?

I have tried mapping the data like so but the data doesn't appear:

React Code:

import data234 from "./realdata-api.json"
import { Fragment } from "react";

const [contacts, setContact] = useState(data234)

{contacts.map((contact) => (
               <Fragment>
                            <h1>{contact.stage}</h1>
                            <h1>{contact.stage}</h1>
                            </Fragment>
 ))}

JSON:

[{
    "word_tracker": {
        "words_tracked": 0,
        "words_used": 1,
        "amount_allowed": 5,
        "title_allowed": 1
    },
    "current_data": [
        {
            "stage": "TCX",
            "cycle": "switch",
            "cycle_period": "2021-07-30",
            "period_end": "2021-08-26",
            "days_into_cycle": 10,
            "days_into_route": 11
        }
    ]
}]

Is the data not mapping because of the headers? In particular, 'words_tracker' and 'current_data'??

Does anyone know how to map the data with the JSON in this format please?

Upvotes: 0

Views: 41

Answers (1)

Ryan Le
Ryan Le

Reputation: 8412

Yes, It easily can.

You will need to change it like so

<>
  {contacts.map((contact) => (
        <Fragment key={contact.current_data[0].stage}>
          <h1>{contact.current_data[0].stage}</h1>
          <h1>{contact.current_data[0].stage}</h1>
        </Fragment>
  ))}
</>

Or change to map through your current_data instead, depend on your needs and JSON structure.

Upvotes: 1

Related Questions