"Master the art of shared styles with styled components - here's how to do

In my quest for a specific design outcome using styled components with shared selectors, I encountered the following challenge:

.styleOne, .styleTwo {
    color: blue; /* shared */
}

.styleOne {
    font-size: 10px;
}

.styleTwo {
    font-size: 20px;
}

Here are some methods I tried:

1 - (This approach did not yield the desired result)

const shared = `color: blue;`

const StyleOne = styled.div`
    font-size: 10px;
    ${shared}
`

const StyleTwo = styled.div`
    font-size: 20px;
    ${shared}
`

2 -

const Shared = styled.div`
    color: blue;
`

const StyleOne = styled(Shared)`
    font-size: 10px;
`

const StyleTwo = styled(Shared)`
    font-size: 20px;
`

3 -

const shared = css`
    color: blue;
`

const StyleOne = styled.div`
    font-size: 10px;
    ${shared}
`

const StyleTwo = styled.div`
    font-size: 20px;
    ${shared}
`

All of the above attempts resulted in something like this:

.styleOne {
    color: blue; /* duplicated */
    font-size: 10px;
}

.styleTwo {
    color: blue; /* duplicated */
    font-size: 20px;
}

While technically the styles were shared from a code perspective, the rules themselves remained duplicated. My objective was to share the CSS rules directly.

To draw an analogy with SASS - I wanted to implement a placeholder instead of a mixin.

To provide context on why I pursued this goal, I aimed to streamline the HTML document for performance reasons. In a large application with numerous shared styles, the style block could become excessively lengthy.

Answer №1

It's difficult to definitively say whether "large apps" will lead to performance issues, as this term is quite ambiguous. The issues could stem from downloading/executing JS, parsing CSS, or fetching other media such as fonts and images. However, styled-components tackles this by applying styles in the head during run-time and deferring them until they are needed in the DOM.

For a demonstration, check out this example and follow these steps:

  1. Inspect the DOM and expand the head section within the Elements tab
  2. Locate and expand the
    <style data-styled="active" data-styled-version="5.2.0"></style>
    tag
  3. Observe how class names are dynamically generated when navigating to different pages
  4. Once classes are assigned, they are reused efficiently

This approach mimics the functionality of css-modules (scoped classes) without additional CSS downloads, automatically handling CSS property prefixes without extra plugins.

Now, the question arises: Is it more advantageous to have more Javascript (due to packaging and running styled-components at runtime) and less CSS (resulting in fewer CSS requests per page), or vice versa? Performance metrics, like conducting a lighthouse test in a production environment, are crucial for determining which approach yields better performance. Otherwise, it becomes purely speculative or based on personal preference.

In any case, some form of render blocking will be encountered, whether it involves downloading/parsing CSS or executing JS.

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

Troubleshooting problem in Spring Boot: Challenges with redirecting to external URL while using AuthenticationSuccessHandler

I recently started using Spring Boot to create a user login system for a REACT web-app. Currently, I am working on redirecting the user to another page within my REACT-app once they have successfully authenticated. To achieve this, I am implementing a cust ...

What causes UI components to fail to update when a user clicks buttons in React?

I have encountered an issue while working on my project. I am currently implementing a function to filter products by category and sort them in the UI when a user clicks on a category button. However, despite updating the array correctly when the button is ...

Issue with Tooltip - Enter Delay functionality not functioning correctly

After setting the enterdelay for the tooltip to 1000 and hovering over my treeview for the first time, I noticed the delay. However, when moving to the next tree item, there was no delay and it immediately popped up. I am currently using version 4.8.3. Do ...

Tips for expanding text within a grid

While working on an auto-fill grid that moves elements to the next line when the width reaches 800px, I encountered an issue with my text inside the grid not stretching. https://i.sstatic.net/OeJ3I.png Below is my CSS code: ul { display: grid; ...

Is there a way to make the edges of this table more curved?

I utilized an HTML code generator to easily create this table, but I am struggling to give it rounded borders. .tg { border-collapse: collapse; border-spacing: 0; } .tg td { border-color: black; border-style: solid; border-width: 3px; font- ...

The fetching of user data is not successfully executed by redux saga

I've been attempting to send an API call to the saga function export function* userLogin, but all I'm receiving is a bad request from the network server. I'm unable to view the console.log output within this function. export function* user ...

I mistakenly imported Line from react-chartjs-2 from the incorrect location

Is there a way to change the position of the yAxes on my line graph so that they are on the right side? I noticed that the Line library used in this link https://codesandbox.io/s/5z3ss is different from mine, which includes React.ForwardRefExoticComponen ...

CSS techniques for positioning a header image

I'm having an issue with using a banner I created in CS6 Illustrator as a header on my website. Despite setting it as the background, positioned at the top and set to "no-repeat", it keeps appearing at the bottom of the header area with around 300px o ...

Executing SetTimeout in Next.js/React framework

let count = 0 function pollDOM() { console.log(count) count++ setTimeout(pollDOM, 3000) // Retry in 3 seconds } pollDOM() The function above runs every 3 seconds producing output like: 1 // Wait for 3 seconds 2 // Wait for 3 seconds 3 // Wait f ...

Is there a way to retrieve two distinct values from an object?

Is there a way to retrieve two target values from an option using useState in react/nextjs? Here is a sample of my api: const movies = [ { id: 1, name: "Fight Club" }, { id: 2, name: "Titanic" }, { ...

Add a custom filter to the active route for a stylish look

I am trying to dynamically change the color of elements in my navbar by creating a filter in my typescript code. I have a string with values like 'greyscale(73%) saturate(1400%)'. How can I apply this string to the fa-icon's filter property ...

Encountering a problem when utilizing webview in react native due to an error with the evaluation of

While utilizing webview for trading charts, I am encountering an issue where a warning is displayed and the URL fails to load. Below is the code snippet used for loading. It seems like the video URI works fine in full screen mode, but other URIs are not ...

Significant challenges with the CSS grid system

I'm brand new to the world of programming and I'm currently attempting to recreate this webpage layout using HTML & CSS: Click here for desired look. My approach so far has been utilizing CSS grid, and while I grasp the concept, I'm faci ...

Tips for choosing an element based on its sequential order in CSS ---Looking to

Within a div that has the class of product, there are multiple hierarchical elements present. Among these elements, two images can be found. The initial image serves as the product thumbnail, while the second image represents the product's rating. Bot ...

Adjust the background color of alternate elements

I am looking to customize the background colors of every other element within the structure provided below: <div class="dets"> <div>Simple Layout</div> <div>Few Pictures/Links</div> <div>Element Uniformity</div> ...

When I switch to a different navigation system, the css class gets removed

Let me clarify what I am looking for: Upon entering the index.php page, LINK_1 button is active. When I switch to LINK_2, it becomes active. I have only one index.php page where I include parts of external pages using PHP. Page_1 https://i.sstatic.net/Yv ...

Creating a clickable image in a React component with code

Within a React component, I want to achieve the equivalent of the following src code found in Laravel Blade: data-src="data:image/;base64,{{ base64_encode(@file_get_contents($auction->thumbnail_link)) }}" What is the best way to do this in a ...

How can we incorporate CSS animations into our current elements?

Recently, I created a fun theme for my website (which I will keep undisclosed) featuring CSS3 animations of falling snow. It adds a cute touch to the site. However, I ran into an issue - I wanted the snow animation to appear over my existing items on the p ...

Sending information to the parent component via props

I am facing an issue where I need to utilize a value generated within a function in the child.js file and then pass it to parent.js in order to filter an array of children based on this value. Child.js const returnDistance = () => { const ...

Issue with Angular 6: Animation with LESS is failing to work post deployment

Hello everyone, I'm facing an issue with my LESS animation. When I deploy my app on the server after using ng build --prod, the CSS animations are not visible in browsers. They work perfectly fine on localhost but fail to work after deployment and I c ...