Enhance your theme property in Styled Components by incorporating numerous style properties

Currently, I am delving into the world of styled components for a fresh project and exploring the theming capabilities it offers. I am finding it challenging to determine the best practice for adding multiple style properties to a single object, essentially creating a form of inheritance. My objective is as follows:

// Establish a set of styles for a specific component within the theme
// For example, every font includes a font-family, weight, size, etc
const theme = {
  fonts: {
    font-family: ...,
    font-weight: ...,
    font-size: ...,
  }
}

// Within the styled component,
// include the multi-line theme, as well as component-specific styling
// and potentially override the theme styles
const Header = styled.span`
  ${props => props.theme.fonts};
  text-decoration: underline;
  ...
`;

Currently, it seems necessary to pass the theme property to each style within the component. Is there a design pattern that could help streamline the code repetition evident in my example above?

Answer №1

One practice I often follow is organizing theme styles in separate files. For instance:

  • MyCustomComponent
    • index.js
    • styles.js //<-- Custom styles for the component
  • theme
    • spacing.js // <-- Standard styles for all components
    • colors.js
    • fonts.js

In the spacing.js file, it might look something like this:

const verticalPaddingSmall = {
  paddingTop: 5,
  paddingBottom: 5,
};

const verticalPaddingMedium = {
  paddingTop: 10,
  paddingBottom: 10,
};

export default function spacing(size, direction, isPadding) {
  // Some logic to determine the correct object based on parameters,
  // such as screen size (tablets vs. phones), etc.
  return verticalPaddingSmall;
}

This code snippet is generated automatically based on configurations set for various screen sizes, resulting in a similar outcome.

In the custom component, I import the common styles, apply them to the component's styles, and make adjustments if necessary. Here's an example from styles.js:

import spacing from 'themes/spacing';
import fonts from 'themes/fonts';

const customStyles = StyleSheet.create({
  main: {
    ...spacing('small', 'vertical', true),
  },
  title: {
    ...spacing('xsmall', 'horizontal', false),
    ...fonts.title,
    fontSize: 25, //<--- Overriding default title values
  },
});

I typically avoid direct style overrides on components, as the shared styles handle variations for tablets and phones, similar to media queries in web development.

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

Tips for modifying the background color of all elements ahead of the element I have selected within a grid

https://i.stack.imgur.com/cW4Lp.png I'm trying to achieve a functionality where clicking on the 20th numbered block changes everything before it to light orange. I have a sandbox code snippet attached and would appreciate any guidance on what needs t ...

Display the table once the radio button has been selected

Before we proceed, please take a look at the following two images: image 1 image 2 I have over 20 fields similar to 'Image 1'. If "Yes" is selected, then a table like in 'Image 2' should be displayed. This means I have 20 Yes/No fields ...

HTML Plant with background removed

I have been attempting to create a tree structure similar to the image provided. However, I am encountering difficulty in getting the background stripes to align properly for a specific row. When resizing the browser window, the stripes do not remain fixed ...

Tips for saving information to a JSON file in Reactjs

Perhaps the real question should be How can I save data to a JSON file using Reactjs and Nodejs? I'm new to React and unsure about which database to use. On a side note, it's simple to read from a json file with var data = require('./d ...

Displaying the :before attribute while concealing the element solely with CSS

I have encountered a situation where I am unable to edit the HTML of a document, specifically a payment page on Shopify, for security reasons. Unfortunately, editing JavaScript is also restricted in this scenario. However, there is a workaround available ...

Trouble with setting up custom static route

Greetings! I am currently working on setting up my project in React and here is my current project structure: -public --w ---dist ----bundle.js ---index.html -server --server.js -src --app.js -webpack.config.js -package.json -.babelrc For my server, I am ...

Alteration in relational shift of division placement

My webpage is divided into three sections with the following proportions: 15% - 65% - 20% In the right section, there is a div with the ID alchemy. I want to set the height of this div using <div style="height:150px;">. However, when I set the heig ...

How can I switch between columns in a dual-column layout?

In my latest project, I utilized CSS Flexbox to create a sophisticated two-column layout that allows toggling each column independently. While this functionality is exactly what I need, I can't help but feel that my current method is somewhat cumberso ...

Is there an equivalent function to onAdd in Material-UI when using MUI Chip?

In my exploration of the latest version of Material-UI, MUI, I observed that the "onAdd" property has been removed. The only function properties remaining are "onDelete" and "onClick". I am interested in generating new chips based on user-input tags. Is ...

What steps should I take to resolve the 'buffer' issue in my jsonwebtoken?

As I am still new to ReactJS and the MERN stack in general, the code in Activate.js below essentially means that when the useEffect() hook is triggered, we will receive the jwt token extracted from the route parameter/url using the {match} props. This toke ...

Automate the process of adding or removing a class created by material ui through programming

Is there a way to dynamically manage the material-UI classes I declared in makeStyles()? Below is the code snippet: import React from 'react'; import { DropboxIcon, GoogleDriveIcon, BoxIcon } from '../components/icons'; import { makeSt ...

Even though I have successfully stored a key value pair in LocalStorage using JSON stringify and setItem, the data does not persist after the page is refreshed

I recently developed a Todo application that runs smoothly, except for one crucial issue - the localStorage data does not persist after refreshing the page. Initially, the localStorage operations functioned properly when there were fewer event handlers in ...

A miniature triangle-shaped bubble crafted with 1px of CSS3 styling

Currently, I am experimenting with CSS3 and creating bubble shapes. However, I have encountered an issue. I am trying to create a triangle with a 1px border, but the result is a thicker triangle than desired. You can view my code on this fiddle : FIDDLE ...

Creating a hover state for a CSS class seems straightforward, but I'm finding it a bit tricky

I am looking to customize my inline menu by changing the last menu item to a different colored box with unique text. I have successfully applied a custom style using the #navbar a.blogbox class, but I am struggling to figure out how to change the hover s ...

Attempting to conceal an HTML 'label' element by employing CSS 'hide' properties

Why is it so difficult to hide a checkbox that says "Remember Me" on my membership site login form? The HTML code snippet causing the issue: <label><input name="rememberme" type="checkbox" id="rememberme" value="forever" /> Remember Me</la ...

Creating tests in JestJs for React components that utilize Context Provider and Hooks

As a newcomer to front-end development, I am currently working on authentication with Okta-React. To pass logged-in user information across multiple components, I'm utilizing React context with hooks. While this approach works well, I encountered an i ...

What role does the single colon play in the setState function when dealing with Arrays?

Adhering to the correct standards of maintaining immutability for this.state const name = this.refs.name.value; const updatedNames = [ ...this.state.names, name ]; //add new name to names array, and finally this.setState({ names: updatedNames }); I am ...

Spin and shift image of a ball using Html 5

Now the image will be moved without rotating. I have implemented moving functionalities, but it only supports IE10. Here is the script I am using: var ball = new Image; window.onload = function () { var c = document.getElementsByTagName('canvas&apos ...

What is the best way to create inline-block elements that stretch the entire width of their container?

How can the input field and button behavior be optimized for this specific display: ...

Using React for Right-to-Left (RTL) Support

How can RTL (Right-to-Left) support be effectively implemented in React applications? Is there a method to customize default <p> and <span> components for RTL support without the need to rewrite existing components? For instance, using a global ...