2

I am getting data from server in which i have to set props in style sheet to change the background color dynamically. but i am getting an error

undefined is not an object (evaluating 'this.props.colorCode')

here is my code

class TopCategoryCard extends Component {
  render() {
    return (
      <View style={styles.container}>

        <View style={styles.CardMainView}>
        <View style={styles.ThirdLayerStyle}>
        </View>
        <View style={styles.SecondLayerStyle}>
         </View>
         <View style={styles.FirstLayerStyle}>
         <Image resizeMode={'contain'} style={styles.CatImageStyle}
          source={this.props.imageUri}
        />
         </View>
        <Text numberOfLines={1} style={{color:'#fff' ,  fontSize:13, top:28  , marginLeft:25  , marginRight:20, fontFamily: "poppinsregular"}}>{this.props.name}</Text>
       </View>

      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    padding:5
  },
  CardMainView:{
    flexDirection:'row',
    borderRadius:4,
    backgroundColor: this.props.colorCode,
    height:80,
    elevation:3,
    shadowColor:'#000',
    overflow:'hidden',
  }
  }

In the Above code i am getting the image and name successfully but facing error in changing the color code kindly help

color changing code

<ScrollView
                      style={{ marginTop:15 , marginLeft:-5  }}
                      horizontal={true}
                      showsHorizontalScrollIndicator={false}>
                      <FlatList 
                        data={this.state.data}
                        keyExtractor={(x, i) => i.toString()}
                        renderItem={({ item }) => (
                          <TouchableOpacity 
                            activeOpacity={0.9}
                            onPress={() =>
                              this.props.navigation.navigate(
                                "JobbyCategorylist",
                                { slug: item.slug }
                              )
                            }
                          >
                            <TopCategoryCard
                              imageUri={{ uri: `${item.url}` }}
                              name={`${entities.decode(item.name)}`}
                              colorCode={item.color}
                            />
                          </TouchableOpacity>
                        )}
                        horizontal={true}
                      />
                    </ScrollView>
user9408899
  • 4,202
  • 3
  • 19
  • 32
S.Hashmi
  • 485
  • 1
  • 8
  • 29

1 Answers1

3

You cannot dynamically assign values to StyleSheet properties. Instead, you can try something like this:

<View style={[ styles.CardMainView, {backgroundColor: this.props.colorCode} ]}>

Don't forget to remove backgroundColor: this.props.colorCode from CardMainView.

user9408899
  • 4,202
  • 3
  • 19
  • 32