Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to refer to a nested array element in Reactjs?

I have a config file which i am refering to in my app.js. I need to use key from a nested element from the array. Here is the array struct. I need to refer to label under contact element.

export const detailConfig = [
  {
    name: "Pr1",
    shortDescription: "Pr1 is a health related product",
    longDescription: "Pr1 is a health related product",
    contacts: [
      { label : "a", link :"1" },
      { label : "b", link: "1" }
    ]
  },

  {
    name: "pr2",
    shortDescription: "Pr2 is a mobile related product",
    longDescription: "Pr2 is a mobile related product",
    contacts: [
      { label : "c", type :"1" },
      { label : "d", type: "1" }
    ]
  }
];

React code:

import "./styles.css";

import {detailConfig} from "./config"

export default function App() {
  return (
    <div className="App">
      {detailConfig.map(detailConfig=>
        <div>
      <h1>{detailConfig.name}</h1>
      <p>{detailConfig.contacts.label}</p>
      </div>

      )}
    </div>
  );
}

code and demo:
https://codesandbox.io/s/objective-wright-ekktrg?file=/src/App.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your contacts property is an array itself. So, you either need to:

  1. Loop/map over it and render its items however you’d like to (https://codesandbox.io/s/peaceful-frost-mnv2fw)
  2. Choose the one item that you want from it (e.g. the first contact only – contacts[0]) and use it instead.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading