Dynamic Styles
A guide to handle dynamic styles in your project.
Why need a guide
Pixel Vue 3 uses Panda as styling engine, Panda is a styling engine that statically analyzable styles in your project and then generates atomic CSS at build time. Therefore we need to handle dynamic styles in Panda's way.
How to write dynamic styles
For example you have an Object that will render dynamic color of title's background. Maybe you will write like this below, but this approach won't work.
vue
<template>
<MpFlex
direction="column"
gap="4"
p="4"
:background="productList[product].color"
>
<MpText size="h1" color="white">{{ productList[product].name }}</MpText>
</MpFlex>
<MpFlex gap="4" p="4" mt="2">
<MpRadio id="radio-1" value="0" v-model="product"> Talenta </MpRadio>
<MpRadio id="radio-2" value="1" v-model="product"> Jurnal </MpRadio>
<MpRadio id="radio-3" value="2" v-model="product"> Qontak </MpRadio>
</MpFlex>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { MpText, MpFlex, MpRadio } from "@mekari/pixel3"
const product = ref("0");
const productList = [
{
name: "Talenta",
color: "brand.talenta",
},
{
name: "Jurnal",
color: "brand.jurnal",
},
{
name: "Qontak",
color: "brand.qontak",
},
];
</script>
with the approach as above, Panda have inability to determine the style values.
Instead we can use style attribute with token()
function to generate dynamic styles.
vue
<template>
<MpFlex
direction="column"
gap="4"
p="4"
:style="{ background: token.var(`colors.${productList[product].color}`) }"
>
<MpText size="h1" color="white">{{ productList[product].name }}</MpText>
</MpFlex>
<MpFlex gap="4" p="4" mt="2">
<MpRadio id="radio-1" value="0" v-model="product"> Talenta </MpRadio>
<MpRadio id="radio-2" value="1" v-model="product"> Jurnal </MpRadio>
<MpRadio id="radio-3" value="2" v-model="product"> Qontak </MpRadio>
</MpFlex>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { MpText, MpFlex, MpRadio, token } from "@mekari/pixel3"
const product = ref("0");
const productList = [
{
name: "Talenta",
color: "brand.talenta",
},
{
name: "Jurnal",
color: "brand.jurnal",
},
{
name: "Qontak",
color: "brand.qontak",
},
];
</script>
The token()
function is contains an object of all tokens by dot-path, allowing you to query for token's raw value at the runtime.
js
/**
* @param {Token} name: name of the token. for ex: 'colors.brand.mekari' or 'sizes.8'.
* @param {string} fallback: fallback value if token is undefined. for ex: '#FF0000' or '8px'
* @return {string} return the value of token or in CSS variable.
*/
function token(name, fallback) {
...
}
Tips
- Use
token.var()
instead oftoken()
to generate value with CSS variable MpText
and some other Pixel components already handle dynamic styles via props
Links
- Read more about dynamic styles in Panda this docs