Passing props into external stylesheet in React Native?

chapeljuice picture chapeljuice · Mar 10, 2017 · Viewed 15.7k times · Source

I'm new to React and React Native. At the moment for each component I'm breaking the code into 2 separate files:

  1. index.js for all the React code, and;
  2. styles.js for the StyleSheet

Is there a way to pass props into the external StyleSheet?

Example: index.js:

Example styles.js:

const styles = StyleSheet.create({
  icon : {
    color: iconColor,
    fontSize: iconSize
  }
});

The code above does not work, but it's more there just to get the point across of what I'm trying to do. Any help is much appreciated!

Answer

Kevin picture Kevin · Jul 1, 2018

I rather to have my styles in a separate file styles.js. Inside styles.js:

export const styles = (props) => StyleSheet.create({
        icon : {
        color: props.iconColor,
        fontSize: props.iconSize
      }
    }

Inside your main class you can pass the value

return (
    <Icon style={styles(this.props).icon} />
  );

Alternatively you can those value directly so it would be

export const styles = (iconColor,iconSize) => StyleSheet.create({
    icon : {
    color: iconColor,
    fontSize: iconSize
  }
}

and inside your main class

return (
    <Icon style={styles(this.props,iconColor, 
this.props.iconSize).icon} />
 );