Search code examples
javascriptreactjsreact-propsmap-function

How do I pass a prop in front of map function in react?


I'm importing some json files as :

import general from './Data/general.json';
import health from './Data/health.json';
import business from './Data/business.json';

And I am trying to iterate through an array "articles" in the json file, the names of the files are same as the category prop I'm passing. So, I want to know how can I change the file from which my map function takes data using prop inputs which change on press of buttons on the navbar.

Trying this, but it doesn't work:

{props.category.articles.map((element) => {

Doing this works but I can't change it according to the prop:

{general.articles.map((element) => {

I've tried enclosing props.category in { },( ), and passing them after declaring them in a const variable but none of it seems to work.


Solution

  • You can try something like this

      const data = {general,health,business};
    
      {data[props.category].ariticles.map(...)}