PanczerTank
PanczerTank

Reputation: 1140

Change prop value based on the value of a variable

I have json objects stored in separate files. I want to pass one of the json objects as a prop into a display component, selecting the json to be passed in based on the value of a query param.

import React from 'react'
import _ from 'lodash'
import PageMain from '../Page'
import test1 from '../jsonData/test1'
import test2 from '../jsonData/test2'
import queryString from 'query-string'

class Page extends React.Component {
  componentWillMount() {
    const location = queryString.parse(location.search)
    // Assume BrandName = 'test1'
    let BrandName = _.get(location,'brand', '')
  }
  render(){
    return(
      <>
        <PageMain brand={BrandName}/>
      </>
    )
  }
}

export default Page

I want to pass in test1 (referencing the imported test1 file) but I am passing in 'test1' a string.

I can't just use a ternary operator or similar because I will have a lot more jsonData.

Upvotes: 0

Views: 87

Answers (1)

yaya
yaya

Reputation: 8273

What you want is convert a string to module name in js.

if it was variable, you could use: window["variableName"] or eval("variableName")

But in your example, they are modules. you should first assign modules to variables or array.

import test1 from '../jsonData/test1' import test2 from '../jsonData/test2'; const tests = {'test1':test1, 'test2':test2};

Then use: <PageMain brand={tests[BrandName]}/>


But i don't recommend this. you can just put your names in an array ['test1','test2'] and fetch json data with another way, not with import.

Upvotes: 1

Related Questions