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

Loop through a JS array and place the React component appropriately

I have a few react components (for eg:like below)

import AloneTab from './tab/AloneTab'
import BiTab from './tab/BiTab'
import CalTab from './tab/CalTab'
import DelTab from './tab/DelTab'

I have an array obj={"Alone":true,"Bi":true,"Cal":false,"Del":true}

Currently, I am rendering the components inside a div like so (just a representation)

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

<div>
 {obj["Alone"]? <AloneTab/>: null}
 {obj["Bi"]? <BiTab/>: null}
 {obj["Cal"]? <CalTab/>: null}
 {obj["Del"]? <delTab/>: null}
</div>

3 components will render ( will not render since "Cal":false)

I have just shown only a few components but there are many more & repeating the code again & again is not nice. Is there a way to loop over the items & renders the components?

I tired

const keys=  Object.keys(obj)
const values=  Object.values(obj)

const tabs = keys.map((tab, index)=>
        values[index] ? <`${tab}Tab`/> :null)

<div>
 {tabs}
</div>

However, this does not work. Is there anyway to make this work?

>Solution :

One method of making this work is to store the object within the array and associate it with the relevant key. Store this along with the boolean value of whether or not it should be shown.
Please see below:

// ./TabOne.js
export default function TabOne() { return <div>Tab One</div>; }
// Repeat for TabTwo, TabThree and TabFour
// App.js
import TabOne from "./TabOne.js";
import TabTwo from "./TabTwo.js";
import TabThree from "./TabThree.js";
import TabFour from "./TabFour.js";

export default function App() {
  const data = {
    "one": { "show": true, "content": <TabOne /> },
    "two": { "show": false, "content": <TabTwo /> },
    "three": { "show": true, "content": <TabThree /> },
    "four": { "show": false, "content": <TabFour /> }
  }

  return (
    <div className="App">
      {
        Object.keys(data).map(key => {
          return data[key].show 
            ? <div key={key}>{data[key].content}</div> 
            : null
        })}
    </div>
  );
}

The above returns:

Tab One
Tab Three
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