Reputation: 1876
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?
Upvotes: 40
Views: 83363
Reputation: 3979
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
Upvotes: 54
Reputation: 6928
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
Upvotes: 34
Reputation: 1006
This is just function scoping rule!
// Outer scope
const Home = (props) => {
// Inner scope
const HEADER_MAX_HEIGHT = 200;
}
console.log(HEADER_MAX_HEIGHT); // Uncaught ReferenceError: HEADER_MAX_HEIGHT is not defined
You don't have access to HEADER_MAX_HEIGHT in the outer scope. So when you try to export it, it just returns an error.
Try with this:
import React from 'react';
import styles from './styles';
const HEADER_MAX_HEIGHT = 200;
const Home = (props) => {
// ...
}
export { HEADER_MAX_HEIGHT };
export default Home;
Now in styles.js:
import { HEADER_MAX_HEIGHT } from './Home';
Upvotes: 3