简体   繁体   中英

How to get a config value into a href as string instead of object object

I have a config file setup that exports a bunch of values...

const dev = {
    ...,
    someRandomLink: 'https://google.com'
}
const config = process.env.REACT_APP_STAGE === 'production' ? prod : dev;
export default {
   ...config
}

I then import this file and try to use the value for a href but it outputs [Object object] .

import someRandomLink from '../constants/config';


...
<a href={someRandomLink}... 

What is the correct way to extract that config variable as a string for the link?

You are exporting an object that contains someRandomLink as property.

When you import the default export, you are importing the entire object and giving it a name, instead of import the specific property.

Try to use it like this

import { someRandomLink } from '../constants/config';

...
<a href={someRandomLink}...

or like this is possible as well:

import config from '../constants/config';

...
<a href={config.someRandomLink}...
export default {
   ...config
}

So you are trying to export as default an object (I guess it's not config, it's dev ). There's 2 ways to export some info from a file:

1) export default myFunction this is importing one single method/object/any value you want to do. Then to import it it's as easy as import myFunction from './myFile' . Since it's a default export, you could name it as you wish: import Hello from './myFile' would work as well.

2) export {myFunction} this is the way to import it as a module, and not a default. With this technique you can import multiple functions like export {myFunction, myOtherFunction, myAwesomeThirdFunction} . The way to import it then it's like import {myFunction} from './myFile' .

In your case you have a mixup between default and the module exports. My suggestion would be:

const config = { // I corrected this dev variable name
    ...,
    someRandomLink: 'https://google.com'
}

export {config}
import {config} from '../constants/config';

...
<a href={config.someRandomLink}... 

Notice that since you exported a method, you need then to access to that property. Otherwise, you would attempt to do something like:

<a href={{someRandomLink: 'myUrl.com', otherProperties: 'otherProperties'}}... 

So that wouldn't work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM