David
David

Reputation: 1

React native var on stylesheer

Is It possible to ad a global variable on a stylesheet Something like this :

const styles = StyleSheet.create({
  bigblue: {
    color: 'blue',
    fontWeight: 'bold',
    fontSize: ´$myglobalvar’
  },
  red: {
    color: 'red'
  },
});

Thanks

Upvotes: 0

Views: 47

Answers (1)

Alexander Kuttig
Alexander Kuttig

Reputation: 426

Yes, this is possible and a recommended pattern to have a consistent design in your app.

  1. You can define your variable inside your file where your stylesheet is in like this:

import React, {Component} from 'react';
import {
StyleSheet,
Text
} from 'react-native';

const defaultFontSize = 16;

class MyTextComponent extends Component {
  render(){
    return (
      <Text style={styles.bigblue}>Test</Text>
    )
  }
}

const styles = StyleSheet.create({
  bigblue: {
    color: 'blue',
    fontWeight: 'bold',
    fontSize: defaultFontSize
  }
});

  1. You can use a central file to set your constants like this:

DesignConstants.js

const DesignConstants = {
  "DEFAULT_FONT_SIZE": 16
}

module.exports = DesignConstants;

MyTextComponent.js

import React, {Component} from 'react';
import {
StyleSheet,
Text
} from 'react-native';
import DesignConstants from './DesignConstants'

class MyTextComponent extends Component {
  render(){
    return (
      <Text style={styles.bigblue}>Test</Text>
    )
  }
}

const styles = StyleSheet.create({
  bigblue: {
    color: 'blue',
    fontWeight: 'bold',
    fontSize: DesignConstants.DEFAULT_FONT_SIZE
  }
});

If your app gets bigger, I would definitely recommend the second possibility.

Upvotes: 1

Related Questions