In my project I have main file with global styles but also I use styles in a individual components. Nonetheless I use the same variables to pass font-size, colours to elements.
I'm not an expert in React but I think that will be nice to move variables to separate file to don't repeat the code. How can I do this in a proper way?
Global styles:
'use strict';
let React = require('react-native');
let {
StyleSheet,
} = React;
let INIT_COLOR = "#fff";
let INIT_FONT_SIZE = 16;
module.exports = StyleSheet.create({
container: {
backgroundColor: INIT_COLOR,
fontSize: INIT_FONT_SIZE
},
});
Component styles:
import React from 'react';
import { View, StyleSheet, Button} from 'react-native';
class ActionButton extends React.Component {
render() {
let INIT_COLOR = "#fff";
let INIT_FONT_SIZE = 16;
return (
<View style={styles.buttonContainer}>
<Button
onPress={this.props.onPress}
/>
</View>
);
}
}
const styles = StyleSheet.create({
buttonContainer: {
backgroundColor: INIT_COLOR,
fontSize: INIT_FONT_SIZE
}
});
export default ActionButton;
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 can export a function or variable from any file. Let us create a file named person. js , and fill it with the things we want to export. There are two types of exports: Named and Default.
Use named exports to export multiple functions in React, e.g. export function A() {} and export function B() {} . The exported functions can be imported by using a named import as import {A, B} from './another-file' . You can have as many named exports as necessary in a single file.
You can just create a file into themes/variables.js
for example. something like this:
export const colors = {
INIT_COLOR: "#fff",
//... more colors here
};
export const fonts = {
INIT_FONT_SIZE: 16,
};
You can also export each individual color if you want, but I'd prefer to export an object of colors.
Then you can import that file in your components:
import React from 'react';
import { View, StyleSheet, Button} from 'react-native';
import { colors, fonts } from 'theme/variables';
class ActionButton extends React.Component {
render() {
return (
<View style={styles.buttonContainer}>
<Button
onPress={this.props.onPress}
/>
</View>
);
}
}
const styles = StyleSheet.create({
buttonContainer: {
backgroundColor: colors.INIT_COLOR,
fontSize: fonts.INIT_FONT_SIZE
}
});
export default ActionButton;
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