홍우지
홍우지

Reputation: 385

React call JSON data with string

import AsukaData from './info/AsukaData.json'
import JinData from './info/JinData.json'

~~~~

const CharArray = [
  'Jin', 'Asuka'
]
{CharArray.map((element,index)=>(
          <Route path={`/${element}`}><CharPage Data={`${element}Data`}/></Route>
     ))}

I want to call JSON data(JinData, AsukaData) with string, but don't know how to do..

Data={${element}Data} is recognized as string. And I want it to be json that is imported above.

Upvotes: 1

Views: 61

Answers (2)

Drew Reese
Drew Reese

Reputation: 202721

Issue

Using the backticks indicates string interpolations/templates.

Data={`${element}Data`}

This takes the string value from the array, and injects and returns a new string value passed to the Data prop.

Solution

If you simply want to map the imported JSON objects then I suggest placing them in the array. Use an object to provide the path key, and the JSON data payload.

import AsukaData from './info/AsukaData.json'
import JinData from './info/JinData.json'

...
const charArray = [
  { path: 'Jin', data: JinData },
  { path: 'Asuka', data: AsukaData }
];

{charArray.map(({ path, data }) => (
  <Route key={path} path={`/${path}`}>
    <CharPage Data={data} />
  </Route>
))}

Upvotes: 1

anshuraj
anshuraj

Reputation: 342

Use an object instead of array to map data with keys

const DataMap = {
  'Jin': JinData, 
  'Asuka': AsukaData
}
{Object.keys(DataMap).map((element,index)=>(
     <Route path={`/${element}`}><CharPage Data={DataMap[element]}/></Route>
))}

Upvotes: 1

Related Questions