"Implementing a Modular CSS Approach and Uniform Styling Across Your App

How can we handle the scenario of implementing specific styling for h1 tags within a modular CSS approach? In the past, this would have been achieved through inheritance in a single stylesheet. For example:

.h1 { font-size: 3rem; /* more styles */ }
.h2 { font-size: 2.5rem; /* more styles */ }
...
.Widget--h1 { font-size: 1.5rem; }

However, this traditional method does not align with a modular CSS strategy. I'm struggling to find a way to accomplish this scenario in a truly modular manner. Below is my initial attempt to address the issue.

Widget.jsx

import React from "react";
import CSSModules from "react-css-modules";
import styles from "./_widget.less";

@CSSModules( styles )
export default class Widget extends React.Component {

    render () {
        return (
            <div>
                <h1 styleName="h1">Chewbacca</h1>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Totam blanditiis, explicabo illo dignissimos vitae voluptatibus est itaque fuga tenetur, architecto recusandae dicta dolorem. Velit quidem, quos dignissimos unde, iste amet?</p>
                <h2 styleName="h2">The "Walking Carpet"</h2>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
                proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
            </div>
        );
    }

}

_widget.less

.h1 {
    composes: h1 from "atoms/text/_text.less";
    font-family: "Comic Sans MS", cursive, sans-serif;
}

atoms/text/_text.less

@import (reference) "~styles/variables/_fonts.less";

/* Headings
   ============================= */
.h1, .h2, .h3, .h4, .h5, .h6 {
    font-weight: normal;
    margin-top: 0px;
    margin-right: 0px;
    margin-bottom: 10px;
    margin-left: 0px;
}
.h1 { font-family: @primary-font; }
.h2 { font-family: @primary-font; }
.h3 { font-family: @primary-font; }
.h4 { font-family: @primary-font; }
.h5 { font-family: @primary-font; }
.h6 { font-family: @primary-font; }

The current implementation works well until using unmodified classes like .h2. The challenge lies in the fact that .h2 is not defined in _widget.less, and there is no global definition for these classes according to modern modular CSS practices. Explicitly composing all headings into each individual class is not the ideal solution either. For instance:

_widget.less

.h1 {
    composes: h1 from "atoms/text/_text.less";
    font-family: "Comic Sans MS", cursive, sans-serif;
}
.h2 { composes: h2 from "atoms/text/_text.less"; }
.h3 { composes: h3 from "atoms/text/_text.less"; }
...

Another proposed solution involves importing general heading styles into the _widget.less file.

_widget.less

@import @import "~atoms/text/_text.less";
.h1 {
    composes: h1 from "atoms/text/_text.less";
    font-family: "Comic Sans MS", cursive, sans-serif;
}

However, this approach leads to duplicated styles whenever styles from _text.less are applied, resulting in code bloat. Any suggestions on how to effectively tackle this issue while adhering to modular CSS principles? I am relatively new to the concept of modular CSS and seeking guidance.

Answer №1

When faced with a scenario like this where you need to combine a default set of classes with customized styles, one approach is to utilize Object.assign:

import defaultStyles from "atoms/text/_text.less"
import widgetStyles from "./_widget.less"

const styles = Object.assign({}, defaultStyles, widgetStyles)

As a result, the variable styles now includes definitions for various headings, leveraging the widget-specific modifications when applicable.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Change the color of the Material UI InputLabel

Seeking assistance with my input label: <InputLabel>NAME</InputLabel> The text is currently displaying in white, which makes it difficult to read against the white background. Can someone provide guidance on how I can change the color to blac ...

Discovering the RGB color of a pixel while hovering the mouse in MapboxGL Js

Looking to retrieve the RGB color value of the pixel under the mouse hover in MapboxGL Js. What is the most effective method to accomplish this task? ...

Encountering a problem with controlling the number of splits allowed

I am encountering an issue with splitting my string using the code below. splitter.map((item1) => { let splitter1 = item1.split("=")[0].trimLeft(); let splitter2 = item1.split("=")[1].trimRight(); }); The content of item1 is as fo ...

Steps for repairing a button positioned at the top of a nested container within a form

My search form includes side filters to help users narrow down their search, with the results appearing on the right. This is just a basic example, as my actual setup involves more filters. However, there is one issue – users have to scroll down the pag ...

Encountering an issue with the user not being updated when logging in through a protected route in React Router v

My current project involves logging in a user using a login component that takes credentials and utilizes Redux Toolkit to manage state. The verification process is handled in the userSlice. I have implemented a protected route to ensure that only logged-i ...

Issue with React event hierarchy

How can I effectively manage state changes in a deep node that also need to be handled by a parent node? Let me explain my scenario: <Table> <Row prop={user1}> <Column prop={user1_col1} /> <Column prop={user1_col2} /> ...

Node.js: The Ultimate Solution for Automatic Data Saving

Currently, I am working on a collaborative project using Node.js, MySQL, and React. I have encountered some difficulties with the ToDo list section. I would appreciate any advice on the best and quickest method to automatically save data or options to the ...

Steps for eliminating double quotes from the start and end of a numbered value within a list

I currently have the following data: let str = "1,2,3,4" My goal is to convert it into an array like this: arr = [1,2,3,4] ...

Can CSS be utilized to define the dimensions and background of a <div>?

Does applying inline styles like <div style="width: ;height: ;background: "> fall under the realm of CSS? ...

Changing padding of a button causes surrounding elements to move?

Trying to make a button in CSS appear "pushed down" on :active, I decided to increase the padding-top by 2px and decrease padding-bottom by 2px. However, this adjustment seemed to affect the margins of other elements for some reason that eludes me. I am c ...

Exploring MaterialUI withStyles to customize disabled switches with a CSS override

As I work on my project using React and MaterialUI, I've encountered a problem with customizing inputs. Despite trying various selectors, I can't seem to change the black color of this particular input. It would be helpful to have a clearer way o ...

Content on the page is not fully visible on mobile devices when the Right-to-Left attribute is applied

I recently added multilanguage support to my blog using the RTL attribute. However, I noticed that when users switch to another language, the page content shifts from LTR to RTL. Everything was working fine until I encountered an issue with a toggle tab o ...

excess margin running along the left side of each page

When visiting http://tadris3.ir/, one may notice a peculiar space on the left side of all pages. Can anyone assist in resolving this bothersome issue? ...

Performing an axios request using form data in a React JS application

I am trying to figure out how to use axios in react js to make a cURL request that is currently working. Here is the cURL request: curl -k --request GET "BASE_URL_SERVER/sendText" --form "user_id='uidxxxx'" --form "sign_id=" Every time I try to ...

What is the best way to establish the state of one property based on another property's state

Coming from the Ember world, I may need some help with what seems like a basic question. I have a component that updates the "scrollPosition" state whenever the window is scrolled. Now, I want to create a new state property called "isScrolledToTop", which ...

Guide to generating a dynamic manifest.json file for Progressive Web Apps using ReactJS

I am working on a project that requires me to generate a dynamic manifest.json file for my PWA (ReactJS). Below are the relevant code snippets: app.service.js: function fetchAppData() { const requestOptions = { method ...

What should I do about the error message from Vercel that is preventing my form component from being accepted?

I am struggling to fix the issue with Vercel continually giving me an error. No matter what I try, it refuses to accept my form component. Error message: Failed to compile. ./pages/createCards/index.js Module not found: Can't resolve '@/compone ...

When invoking the fetch method on the PHP controller, it encounters an error during the execution of

Here is an error I encountered while working with ReactJS: VM345:1 Uncaught (in promise) SyntaxError: Unexpected end of JSON input To provide some context, I have a PHP controller with a delete endpoint. Below is the code snippet for this endpoint. php c ...

Renew The Dining Surface

I am looking for a way to update the table content without refreshing the entire page. I am using HTML, CSS, and JavaScript to display the current data from my sqlite3 database. Any tips on how to achieve this would be appreciated. ...

Exploring the images in a continuous loop

Looking to create a unique image looping effect using HTML, CSS, and Jquery/Javascript. The concept is to display several images on one page that do not move, but loop through them one at a time while displaying text above the current image. For example, ...