Home > Mobile >  How to fix "Not A Function" Error from React Native while declaring Dynamic Styles
How to fix "Not A Function" Error from React Native while declaring Dynamic Styles

Time:12-31

I'm following a tutorial and I currently have this code where I am trying to change the color of a background based on a prop... This is what it looks like

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

const SomeComponent = ({ bgColor }) => (
  <View style={styles.wrapper(bgColor)}>
    <Text style={styles.text}>3333</Text>
  </View>
);

const styles = StyleSheet.create({
  wrapper: color => ({
    flex: 1,
    backgroundColor: color,
  }),
  text: {
    color: 'red',
  },
});

I keep getting a styles.wrapper is not a function Please how do I fix this...

CodePudding user response:

You cannot declare a StyleSheet function like you did.

Alternatively, you can declare a JS function that passes the same style with different colors according to the arguments you pass.

You can do that as follows:

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

const myStyle = (color) => {
    return {
        flex: 1,
        backgroundColor: color,
    }
};

const SomeComponent = ({ bgColor }) => {
    <View style={this.myStyle(bgColor)}>
        <Text style={styles.text}>3333</Text>
    </View>
};

const styles = StyleSheet.create({
    text: {
        color: 'red',
    },
});
  • Related