React Native Constants File

Tiempo de lectura: 2 minutos

Reading time: 2 minutes

Good afternoon, everyone,

In today’s tutorial, I’m going to show you how to create files with constants so that they are accessible from any point in our application and keep everything more organized.

This applies both to components and screens.

In my case, I’m going to apply it in a component called Button.js.

import React from "react";
import { StyleSheet } from "react-native";
import { Button } from 'react-native-paper';

// Button component
const Button = (props) => {

    // Constructor parameters are passed through props
    const { text, onPress } = props;

    return (
        <Button style={[styles.button]} mode="contained" onPress={onPress}>{text}</Button>
    )
};

export default Button;

const styles = StyleSheet.create({
    button: {
        backgroundColor: '#FF7000',
        marginLeft: 5,
        marginRight: 5,
        marginTop: 10,
    },
});

This shows us a Button component as follows:

But what we want to avoid is repeating color code in components and screens. If we decide to change the design of our application, we would have to change it in all screens, components, etc.

Next, I’ll show you how to do it. We’re going to change the orange color to blue, for example, to see the result.

  1. Create a folder called “constants” (for example) in the root of your project, and inside it, create the following file called “Colors.js” where we will store all the colors used in our app:

2. Add the following code to the Colors.js file:

const generalBlue = 'blue';

export default {
    generalBlue,
}

Now let’s use it in our Button component. As you can see, we import the Colors.js file from the constants folder to access it, and in the styles, instead of using individual colors, we use the constant.

import Colors from "../constants/Colors";
backgroundColor: Colors.generalBlue,
import React from "react";
import { StyleSheet } from "react-native";
import { Button } from 'react-native-paper';

import Colors from "../constants/Colors";

// Button component
const Button = (props) => {

    // Constructor parameters are passed through props
    const { text, onPress } = props;

    return (
        <Button style={[styles.button]} mode="contained" onPress={onPress}>{text}</Button>
    )
};

export default Button;

const styles = StyleSheet.create({
    button: {
        backgroundColor: Colors.generalBlue,
        marginLeft: 5,
        marginRight: 5,
        marginTop: 10,
    },
});

So it would look like this:

Whatever color we set for this constant will change in all places where it is used without the need to update each one individually. Therefore, we ensure that it is changed throughout our app.

I hope you like it and find it useful.

Have a great weekend!

Leave a Comment