I have a FlatList
with objects, and every object has a certain color. I want to pass that color to the style of the items of the FlatList
.
PlayList class:
class Playlist {
id: number;
name: String;
color: String;
songs: Song[];
constructor(id: number, name: String, color: String) {
this.id = id;
this.name = name;
this.color = color;
this.songs = [];
}
}
Playlists Component:
class Playlists extends Component<Props, State> {
constructor(props) {
super(props);
this.state = {
playlists: [
new Playlist(0, 'Favorite Songs', 'purple'),
new Playlist(1, 'Rock', 'green'),
new Playlist(2, 'Pop', 'blue'),
new Playlist(3, 'Electronic', 'yellow'),
],
};
}
render() {
return (
<FlatList
data={this.state.playlists}
renderItem={({item: playlist}) => (
<View>
<View style={styles.namePart}>
<View
style={{
backgroundColor: playlist.color, //Here I want to pass the color of the Playlist object to the backgroundColor property, but it does not work
}}
/>
<Text style={styles.name}>{playlist.name}</Text>
</View>
<Text style={styles.count}>{playlist.songs.length}</Text>
</View>
)}
/>
);
}
}
I get en error on that: No overload matches this call. Type '{ backgroundColor: String; }' is not assignable to type 'StyleProp<ViewStyle>'
I have also tried the following:
<View
style={StyleSheet.create({
backgroundColor: playlist.color,
})}
/>
But here it shows the following error: Type 'String' is not assignable to type 'ViewStyle | TextStyle | ImageStyle'.
But when I create a style in const style = StyleSheet.create({})
and pass for example backgroundColor: 'blue'
, this works. Is 'blue'
not a String in this case? I don't really get this.
How do I have to change my code that it works?