Kamalesh kunwar
Kamalesh kunwar

Reputation: 272

How can i fetch a value from a const using a key from another js class n react-native?

I am able to get to data using a key from a const within a same class, But how can I achieve the same result while placing the const in another js file ? I wanted a value 'Afganistan' while i send a key as '1'.

CountryCode.js file: 
  const CountryCode = {
    '1': 'Afghanistan',
    '2': 'Albania',
    '3': 'Algeria',
    '4': 'American Samoa',
    '5': 'Andorra'
  };

HomePage.js file:
  import CountryCode from'./CountryCode';
  render() {

    return (
      <View style={styles.MainContainer}>

         <Text style={styles.listCountry}>{CountryCode['1']}</Text>

      </View>
    );
}

Upvotes: 0

Views: 487

Answers (2)

narayansharma91
narayansharma91

Reputation: 2353

First of all you have to export data (array) from CountryCode.js file like below.

CountryCode.js file: 
  export default {
    '1': 'Afghanistan',
    '2': 'Albania',
    '3': 'Algeria',
    '4': 'American Samoa',
    '5': 'Andorra'
  };

Upvotes: 0

Daniel Doblado
Daniel Doblado

Reputation: 2848

Add export default CountryCode at the end of CountryCode

 const CountryCode = {
    '1': 'Afghanistan',
    '2': 'Albania',
    '3': 'Algeria',
    '4': 'American Samoa',
    '5': 'Andorra'
  }

export default CountryCode

Now the variable should have the value in the other file.

Upvotes: 1

Related Questions