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?
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' .
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.
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.
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' .
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With