0

I want to have 4 boxes, each box with a different color, and I want to do that loading each style from map(). The below code doesn't compile, I wrote it so you understand what I'm trying to do. The error derives from inside the View at styles.{box.name}, I want instead of {box.name} to put array's elements so the function can take Stylesheet's props.

export default function Imagesfun() {
    const array = [{
        name: "box1",
    },
    {
        name: "box2",
    },
    {
        name: "box3",
    },
    {
        name: "box4",

    },
    {
        name: "box5",
    }]
    return (
        <View style={styles.container}>

            {array.map(box => <Text style={styles.{box.name}} key={box.name}>{box.name}</Text>)}

        </View >
    )
}

const styles = StyleSheet.create({
    container: {
        justifyContent: "space-around",
        alignContent: "center",
        backgroundColor: 'black',
    },
    box1: {
        backgroundColor: 'lightblue',
    },
    box2: {
        backgroundColor: 'lightred',
    },
    box3: {
        backgroundColor: 'lightyellow',

    },
    box4: {
        backgroundColor: 'lightpurple',

    },
    box5: {
        backgroundColor: 'lightgreen',
    },
});
Giannhs Ker
  • 97
  • 1
  • 8

2 Answers2

1

Change {styles.{box.name}} to {styles[box.name]}. Check this Q & A for more details.

Prathap Reddy
  • 1,688
  • 2
  • 6
  • 18
1

Try as following:

<View style={styles.container}>
  {array.map(box => <Text style={styles.[box.name]} key={box.name}>{box.name}</Text>)}
</View >