Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

es6 : how to import const after export?

I apologise for my lack of knowledge. I want to import a const value inside a file. I have two files Home.js and styles.js in the same directory.

Home.js

import React from 'react'; import styles from './styles';  const Home = (props) => {      const HEADER_MAX_HEIGHT = 200;  }  export { HEADER_MAX_HEIGHT }; export default Home; 

And in styles.js

import { StyleSheet } from 'react-native' import { HEADER_MAX_HEIGHT } from './Home';  export default StyleSheet.create({     header: {         height: HEADER_MAX_HEIGHT     } }); 

but i am getting this error

Can't find variable : HEADER_MAX_HEIGHT

how can i access that variable in styles.js?

like image 787
bazi Avatar asked Nov 12 '16 07:11

bazi


People also ask

How do I export and import const?

To import a constant from another file in React: Export the constant from file A , e.g. export const str = 'First' . Import the constant in file B as import {str} from './another-file' .

Can I export const in JS?

After the export keyword, you can use let , const , and var declarations, as well as function or class declarations. You can also use the export { name1, name2 } syntax to export a list of names declared elsewhere.

Can I export const?

Use named exports to export constants in JavaScript, e.g. export const A = 'a' and export const B = 'b' . The exported constants can be imported by using a named import as import {A, B} from './another-file. js' . You can have as many named exports as necessary in a file.

How do I import a variable from another file in React?

To import a variable from another file in React:Export the variable from file A , e.g. export const str = 'hello world' . Import the variable in file B as import {str} from './another-file' .


2 Answers

You should probably structure your code in a completely different manner.

A good rule is to keep all constants in a separate file, away from all Views.

Try creating a file for all App Constants. Constants.js is a good choice.

Then put constants in like this:

const Constants = {   HEADER_MAX_HEIGHT: 200,   OTHER_THINGS: 'whatever' } export default Constants 

Then you can import your constants wherever you need them.

import Constants from '../Folder/Constants' 

and use like such

const x = Constants.HEADER_MAX_HEIGHT 
like image 102
parker Avatar answered Oct 05 '22 23:10

parker


Try:

Home.js

import React from 'react'; import styles from './styles';  export const HEADER_MAX_HEIGHT = 200;  const Home = props => <h1>Home</h1>;  export default Home; 

styles.js

import { StyleSheet } from 'react-native'; import { HEADER_MAX_HEIGHT } from './Home';  export default StyleSheet.create({   header: {     height: HEADER_MAX_HEIGHT,   }, }); 

Your HEADER_MAX_HEIGHT needs to be within the Home.js file but outside of the Home Component. You can read about it here: Javascript Scope

like image 38
Ilanus Avatar answered Oct 05 '22 22:10

Ilanus