Skip to content

Compound variants

Compount variants
All platforms
2.0.0

Unistyles does not have first-class support for compound variants, but you can easily create them yourself.

First, you need to define your variants as described in this guide.

const stylesheet = createStyleSheet({
container: {
variants: {
size: {
small: {
width: 100,
height: 100
},
medium: {
width: 200,
height: 200
},
large: {
width: 300,
height: 300
}
},
color: {
red: {
backgroundColor: 'red'
},
green: {
backgroundColor: 'green'
},
blue: {
backgroundColor: 'blue'
}
}
}
}
})

The easiest way to create a compound variant is to use the dynamic function.

const stylesheet = createStyleSheet({
container: {
variants: {
size: {
small: {
width: 100,
height: 100
},
medium: {
width: 200,
height: 200
},
large: {
width: 300,
height: 300
}
},
color: {
red: {
backgroundColor: 'red'
},
green: {
backgroundColor: 'green'
},
blue: {
backgroundColor: 'blue'
}
}
}
},
extraStyle: (size, color) => {
if (size === 'small' && color === 'red') {
return {
borderWidth: 1,
borderColor: 'black'
}
}
if (size === 'medium' && color === 'green') {
return {
borderWidth: 2,
borderColor: 'black'
}
}
return {}
}
})

You can now merge both styles into one component, as with the regular StyleSheet.create:

const MyComponent = ({ size, color }) => {
const { styles } = useStyles(stylesheet, {
size,
color
})
return (
<View style={[styles.container, styles.extraStyle(size, color)]} />
)
}