Search code examples
reactjscss-modulesreact-css-modules

Updating CSS Module @Value with React


I am using CSS module along with react. I want to change the border-radius dynamically from react. In the box.css , i set the border-radius as radiusValue. My goal is to modify the value of radiusValue from a react component. Is that possible? I couldn't find any solution related to updating the @value variable.

Thank you

inside box.css:

@value radiusValue:0px

.box{
    height: 200px;
    width: 300px;
    border: 10px solid #595252;
    border-radius: radiusValue;
    padding: 100px;
    margin: 50px;
}

Solution

  • You can not do that with CSS pre-processors, because they generate static files that can not be changed on the fly,
    but you can do this with pure CSS - specifically with CSS Custom properties.

    CSS file:

    :root {
      --radius-value: 0px;
    }
    
    .box {
        height: 200px;
        width: 300px;
        border: 10px solid #595252;
        border-radius: var(--radius-value);
        padding: 100px;
        margin: 50px;
    }
    
    

    JS file

    element.addEventListener("click", () => {
      root.style.setProperty("--radius-value", "20px")
    })