What are your thoughts on combining styled-components with unique custom styles?

I've been enjoying exploring the world of styled-components, but I'm struggling a bit with the concept of breaking everything down into components and how to customize styles for specific use cases. For instance:

<Flex>
   <MyStyledTitle>Hello I am a Title</MyStyledTitle>
   <MyStyledBodyText>blah</MyStyledBodyText>
</Flex>

Let's say I wanted to make the following customizations for this scenario:

  1. Make the title grey (subdued text color),
  2. Add a right margin of 100px to the body text (for reasons unknown).

In the styled-components approach, the first part could be achieved like so:

<MyStyledTitle colorTint='subdued' /> 

or even

<MyStyledTitle>
    <SubduedText>MyTitle</SubduedText>
</MyStyledTitle>

Maybe using a prop for the title that allows you to choose between subdued text or another child component that defines the grey text.

But what about the second option...

<MyStyledBodyText style={{paddingRight: 100}} /> 

Inline style? Use a Grid or layout component around it?

When does something become a specific styled-component, and if not, how can smaller style changes be customized?


Although I really appreciate the idea of eliminating the connection between a component and a class name, I find myself torn between the traditional approach of having a 'style sheet' file containing all the classes and modifier CSS, and then utilizing a presenter to select from various combinations of CSS classes.

I may be missing something here, but I would love to see some comprehensive examples of styled components in action. Any suggestions or links would be greatly welcomed!

Answer №1

In our project, we have integrated styled-components extensively. We follow a few key patterns and conventions:

  1. Styled components are not shared across React Components; in extreme cases, they are extracted into external files for export.
  2. We primarily use the styled.div component, although we do utilize other HTML elements like buttons and table cells as well.
  3. We define unique styles for different instances of the same HTML element or React Component. This approach is elaborated upon in the FAQ section of the styled-components documentation found at here.

In response to your inquiry, transitioning away from traditional stylesheets and exploring combinations of styles has been beneficial for us. However, managing unit tests in this setup can be slightly challenging.

Thank you.

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

Having trouble getting 'npm start' to run in your React Native setup?

Hey there, As a beginner in programming, I am currently setting up my toolchain and initiating a new React Native project. If necessary, download a code editor (+ extensions), git, npm Install the Expo app on your mobile device. Whether it's iOS or A ...

Tips for adjusting the size of numbers (e.g. 0, 1,4..) using CSS

I have a paragraph on my website that contains a phone number and an email address within the header section. I have styled them to be the same font-size: small, but for some reason, the phone number appears slightly larger than the email address when view ...

Strategies for resolving memory leaks in Next JS

I ran into an issue while trying to fetch the API which resulted in the following error message: Warning: Can't update a React state on an unmounted component. Although this is harmless, it suggests a memory leak in your application. To resolve this, ...

What is the reason for node executing both of these handlers on the server?

My node app is set up with two handlers, one for requests to the root URL and another for the slug. However, when I visit the root or slug URLs, the app crashes and I receive this error: url is pointing to root url has a slug throw err; // Rethrow non-MySQ ...

Tips for turning off the auto save password option on browsers for user registration forms

Is there a way to prevent browsers from saving passwords on the add users form? I've tried using autocomplete="off" but it doesn't seem to work for saved passwords. I've searched extensively for a solution but haven't found the right on ...

JavaScript - find matches and differences between two arrays based on keys, resulting in four arrays showing the matches and differences for each

Custom Interface - interface Person { name: string; age: number; city: string; address?: string; } Data Arrays - const people1: Person[] = [ { name: "daniel", age: 21, city: 'NYC' }, { name: " ...

Experimenting with a React component that is monitoring states

Consider a scenario where I have a basic React functional component that primarily monitors changes in context and displays a view of the state from that context. export default function Observer(props) { // Utilize a separate dispatch context for perfor ...

The video does not begin playing automatically after utilizing react-snap

I included a background video in my react app that auto-plays upon page load and functions perfectly. Here is the JSX code I used: <video autoPlay loop style={{ backgroundImage: `url(${topVideoImage})`, }} muted playsInl ...

The data is being retrieved accurately, but unfortunately, it is not showing up correctly when displayed

Currently facing an issue with displaying returned data in a p and textarea element. The function I'm utilizing successfully fetches each key from the comments node and retrieves the comment title and message as expected... function loadComments() { ...

Tips for transferring information to various templates with *ngFor and *ngIf in Angular 4

I'm working with an object that looks like this let obj = [{ templateId: 1, name: "Template 1" }, { templateId: 2, name: "Template 1" }, { templateId: 3, name: "Template 1" }]; Within my HTML Template, I'm attempting to ...

Encountering a TypeError in Mongoose: Unable to access properties of undefined while trying to read 'find'

Encountering an issue with the error message, TypeError: Cannot read properties of undefined (reading 'find'), specifically pointing to this block of code: app.get('/Organizations', (req,res) => { Organizations.find({}).then((organiz ...

Guide on how to beautify HTML and generate output files in the identical directory as the current one

Hey there! I'm currently working as a junior front-end developer and have recently delved into using gulp. One of the challenges I face is dealing with HTML files received from senior developers that aren't well-formatted, containing excessive wh ...

Implementing Compulsory User Logout using jQuery Ajax

I'm attempting to ensure that the user logs out of the system before closing the browser. Here is the code I have come up with: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <script type="text ...

Looking to utilize vue.js to alter the color of the <li> element when a select option is chosen

I'm a beginner in vue.js and I'm attempting to change the background color by using the select option. Despite trying the cueCardsColor method, nothing seems to be happening. <ul> <li :class="+ cueCardColor"> <sele ...

Expanding content does not increase CSS height to 100%

I recently had a question similar to this one, but I struggled to explain it properly without a JSFiddle. After spending about 20 minutes creating this fiddle, I hope it helps clarify my issue! Check out the JSFiddle here In my project, I have expandable ...

The use of dangerouslySetInnerHTML in a React application is causing issues when trying to include Segment.io tags

Currently, I'm integrating Segment.io into my react/NextJS application. I'm mimicking the pattern established by a previous function that deals with Google Analytics const segmentWriteKey = 'xyz'; export default class CustomDocument ...

Creating a simulation of a sun-like vector rotating around a sphere in three.js

Currently, I am attempting to modify this code (which was originally based on an implementation found here). While I have successfully achieved the desired visualization and rendering effects, my goal now is to introduce realistic movement into the animati ...

Can Vue.js support two-way data-binding without the use of an input element?

Here is the code snippet that I'm working with: <div id="app"> {{ message }} </div> JavaScript: myObject = {message:"hello"} new Vue({ el: '#app', data: myObject }) When I update myObject.message, the content within th ...

Can you explain the distinction between using "require" to return a module and accessing the actual object in node.js?

When working with node.js, the commonly used method to include modules from other files is by using "require", whether it's from our own code or third-party libraries. But for me, there seems to be some confusion regarding the distinction between the ...

Delayed callback on blur

I am developing an AutoComplete feature in React that displays a list of suggested completions as the user types into a text box. When a suggestion is clicked, it should trigger a callback function, and the dropdown should disappear when the text box loses ...