July 22, 2021

How to apply styles dynamically In SPFx web part?

Introduction:

We implemented an intranet portal for a Real Estate Agency based out of Bellevue, Washington, United States. We came across a requirement to apply styles dynamically in the custom SPFx webpart based on the color selected in the property panel of the SPFx webpart. Let's see how this functionality can be achieved.

Requirement:

We need to apply the color of text based on the color selected in the property panel. In the property panel, we have added a textbox, where users can add a 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. In the CSS file, we need to define the color of the 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 a variable 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 appended 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 file as well.

Conclusion:

This is how we can apply dynamic styles. Hope this helps you!

If you have any questions you can reach out our SharePoint Consulting team here.

No comments:

Post a Comment