How To Apply Styles Dynamically Using JavaScript In SPFx Web Part

Introduction

In this blog, we will learn how we can apply styles dynamically based on the color change in the property panel of the SPFx web part.

Requirement

We need to apply the color of text based on the selected color in the property panel. In the property panel, we have added a text box, where users will add color code or a color name that they want as the text color.

Implementation

We have applied the class name for the div where we are showing texts and in the CSS file, we need to define the color of text using variables.

The CSS will be as below,

.ProjectTitle{
    color: var(--projectTitleColor);
}

And our HTML will be as below,

<div className="ProjectTitle">
    Intranet Portal    
</div>

As we can see, in the CSS we have used variables for applying the color. Now we will assign the value to this variable.

First, we will get the value from the text box of the property panel as below,

var colorName = this.props.TextColor;

Now we will use colorName variable, to assign a color to the style’s variable. 

let div = document.createElement('style');
div.innerHTML = ':root {-- projectTitleColor: ' + colorName + ' }';
document.getElementsByTagName('head')[0].append(div);

So here we created a new element for style and append this element in the head element of the page.

Whatever value we assign to the variable – projectTitleColor, it will assign to the color style in the CSS file.

Here in this example, we have used a CSS file, but you can also use the same steps for scss as well.

Conclusion

This is how we can apply dynamic styles. Hope this blog will be helpful!