Search code examples
cssreactjsstyled-components

How I can check condition base on the value of css custom property in React


I have a css custom property contain the value of theme color: var(--themeColor).

And I want to check the value of theme color whenever it is white then I can change the value of background-color to another value.

For example:

.btn {
    background-color: var(--themeColor) == "white" ? "red" : var(--themeColor);
}

Solution

  • You can read a css variable value using this js snippet:

    getComputedStyle(document.documentElement).getPropertyValue('--themeColor').trim();
    

    So then with styled-components you can achieve this ternary operator test to get the color:

    .btn {
        background-color: ${getComputedStyle(document.documentElement).getPropertyValue('--themeColor').trim() === "white" ? "red" : "var(--themeColor)"};
    }