iTranslated by AI
How to provide multiple fallback values for the same property in Chakra UI
When making specifications in CSS that are only available for certain values, you might write multiple declarations to provide fallback values.
Although it's not used much lately, for things like svh or dvh that are specific to certain browsers like Safari, it looks like this:
.some-container {
height: 100vh;
height: 100dvh;
}
In cases like Chakra UI, you write in an object format, so even if you write <Box height={"100vh"} height={"100dvh"} />, one will overwrite the other.
On the other hand, if you do something like <Box height={["100dvh","100vh"]} />, it will be treated as responsive styles.
So, I wondered how to handle this situation.
Solution 1: Writing in a double array format while allowing type errors.
Although a TypeScript error occurs, it seems it can be set with a description like the following:
<Box
// @ts-ignore
height={[["100vh","100dvh"]]}
>
In the above, ts-ignore is used to suppress the type error.
While it is technically possible, I couldn't find any relevant code or test cases even after a quick look at the Chakra UI source code, so it might be an unintended behavior or a bug.
Solution 2: Using the css property
By using the css property, you can inject raw CSS, so this is also possible.
In this case, no type error occurs, but note that there is no handling for the CSS part, so care is needed.
<Box css={`height: 100vh; height: 100dvh;`} >
Solution 3: Resolving with the sx property and &
When using sx, you can achieve this by making full use of &.
Since & is replaced by the assigned class name of the element itself, it allows you to forcibly apply multiple styles that reference yourself.
<Box
sx={{
height: "100vh",
"&":{
height: "100svh"
}
}}
/>
With sx, Chakra's theme and other features are also available, which provides advantages over the css property.
Furthermore, if you want to increase the number to three or four, although it's quite a stretch, you can also solve it by adding a space or a * that doesn't affect specificity, as shown below.
<Box
sx={{
bg: "red.200",
"&":{
bg: "blue.200"
},
" &":{ // Fooling JS by adding a space
bg: "yellow.200"
},
"* &":{ // A * can also be used instead of a space
bg: "green.200"
},
}}
/>
Basically, the styles defined further down take precedence, but care is needed as something like div & would change the CSS specificity.
Discussion