How to useDynamic Styling with Scoped Variables in CSS
In this approach, we are using the Dynamic Styling with Scoped Variables in which we have created Custom CSS in JavaScript utility which is “scopedVariables.js”. In this the styles for the “ProfileCard” are been specified, incorporating CSS variables that control the styling color. In the “ProfileCard” component, we have used the scoped variables and CSS variables for actually applying the dynamic styling. This component also accepts the props like name, jobTitle, etc. So by injecting the props into the scoped styles, we created component-specific styles that are actually dynamic and also isolated and avoid clashes.
Syntax:
const generateScopedStyles = (componentName, variableValue) => {
return `
.${componentName} {
--custom-variable: ${variableValue};
/* Other styles using the custom variable */
}
`;
};
export default generateScopedStyles;
Example: Now, add the below code in the respective files as shown in the above directory structure:
Javascript
// components/ProfileCard.js import React from "react" ; import generateScopedStyles from "../utils/scopedVariables" ; const ProfileCard = ({ name, backgroundColor, jobTitle, }) => { const componentName = "profile-card" ; const dynamicStyles = generateScopedStyles( componentName, backgroundColor ); return ( <div className={componentName} style={{ backgroundColor }} > <h2>{name}</h2> <p>{jobTitle}</p> <style jsx>{dynamicStyles}</style> </div> ); }; export default ProfileCard; |
Javascript
// pages/index.js import React from "react" ; import ProfileCard from "../components/ProfileCard" ; const Home = () => { return ( <div> <h1 style={{ color: "green" }}> w3wiki </h1> <h3> Approach 2: Using Dynamic Styling with Scoped Variables </h3> <ProfileCard name= "Mark Zuckerberg" jobTitle= "CEO of Facebook" backgroundColor= "lightblue" /> <ProfileCard name= "Elon Musk" jobTitle= "CEO of Twitter" backgroundColor= "lightpink" /> </div> ); }; export default Home; |
Javascript
// utils/scopedVariables.js const generateScopedStyles = ( componentName, variableValue ) => ` .${componentName} { --profile-card-bg-color: ${variableValue}; background-color: let(--profile-card-bg-color); padding: 20px; border-radius: 10px; } `; export default generateScopedStyles; |
Step to run the application:
Now, run the application by executing the below command in the terminal:
npm run dev
Output:
Controlling the specificity of CSS Modules in a Next.js App
CSS Modules are one of the popular techniques that are used for local scoping CSS in JavaScript behavioral applications. In Next.js applications, CSS Modules are mostly used to generate the unique class names for our styles, preventing them from conflicting with the styles from different components or libraries. In this article, we will look into the approaches for Controlling the specificity of CSS Modules in a Next.js App.