Implement consistent styling across several elements within a component

const GreenRow = styled.div`
  background-color: green;
`
const RedRow = styled.div`
  background-color: red;
`
const YellowRow = styled.div`
  background-color: yellow;
`
const GreyRow = styled.div`
  background-color: grey;
`

const MyComponent = () =>
  <div>
    <GreenRow>Green row</GreenRow>
    <div>Blue row</div>
    <RedRow>Red row</RedRow>
    <YellowRow>Yellow row</YellowRow>
    <GreyRow>Grey row</GreyRow>
  </div>

Incorporating styled-components to customize elements within a component.

The objective is to implement additional styling (e.g. font-weight) across specific components in a unique manner. Some of these components are already formatted using styled-component, creating an added layer of design complexity.

One approach could involve defining the style with a designated classname, which would then be applied to each applicable element. However, it appears that generating a classname through styled-components is not feasible. Additionally, introducing external styling files outside of the component structure is not desirable.

An alternative method might entail utilizing styled-component's css library to render the style application universally (refer to code snippet below) and integrating it within relevant styled-component definitions. Nevertheless, this approach may necessitate converting certain elements into styled-components solely for this purpose if they lack existing formatting.

const FontWeight = css`
  font-weight: 600;
`

Exploring efficient strategies for implementing this secondary level of customization seamlessly.

Answer №1

If you want to incorporate a function into the template literal, you can utilize the props from the component with

${props => props.component_name && css
... }.

In this example, I am customizing the styling for Green within the Row:

import styled, { css } from styled-components

const Row = styled.div`
  /* Generic row styling */
  font-weight: 600;

  /* Unique row styling */
  ${props => props.Green && css`
    background: green;
  `}

`

Keep in mind that you will also need to import css!

To render a green row with the additional property, simply do:

render(
  <div>
    <Row>Normal Row</Row>
    <Row Green>Green Row</Row>
  </div>
);

The green row will inherit the basic styling from regular rows and apply the specific rules defined for it.

I hope this explanation clarifies things for 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

IE z-index anomaly

My line of floated divs reveals a popup when hovered over, but the popup appears under the following divs instead of on top. I've tried using z-index with no success to fix this issue. UPDATE: The problem has been resolved with some assistance, but i ...

Adjust the size using padding alone

My CSS specifies font size of 14px, line height of 14px, and padding of 7px on the top and bottom. The total should be 28px. When I apply these styles in a div, it results in a height of 28px. However, when applied to a ul li a element, the height becomes ...

Creating an HTML table with collapsed borders and hidden rows/columns using the `border-collapse

I am facing a situation where I have a table with multiple lines as shown below: <table> <tr id="line1"><td>Line</td><td>1</td></tr> <tr id="line2"><td>Line</td><td>2</td></t ...

Developing an interactive contact page using bootstrap technology

I am looking for a way to structure my contact page using Bootstrap. https://i.sstatic.net/e3TCu.png If you're interested, the code for this layout can be accessed here: https://codepen.io/MatteCrystal/pen/xxXpLmK <div class="container" ...

The continuation of unraveling the mystery of utilizing `overflow-y:scroll` in a horizontal slider

As a beginner, I realized too late that adding code in comments is not an option. Consequently, I decided to create a new question and ask for your assistance once again. To optimize the use of space, I have implemented bxSlider with fixed dimensions (wid ...

Misplacement of HTML head tags

Is it a grave error in this layout that H1 isn't the first rendered head element? Is there any way to correct this issue? Given that both columns have variable lengths, I am struggling to find a workaround. Reference I was requested to provide a ref ...

Invoke a method from a related component within the same hierarchy

Imagine this scenario: You're working on a reusable item carousel. The slide track component and the slide navigation component need to be independent and in a sibling relationship so you can position the buttons wherever you want. But how do you trig ...

Using the spread syntax in the useState function

I'm facing an issue where when I use the setItemPressed function to change the value of itemid to false, it doesn't work as expected. However, if I only pass in {[itemid]: false} as an argument, it does change successfully but all other ids are r ...

I am seeking assistance with generating a printed list from the database

Struggling for two full days to successfully print a simple list from the database. Take a look at the current state of the code: function CategoriesTable() { const [isLoading, setLoading] = useState(true); let item_list = []; let print_list; useEffect(( ...

Tips to prevent the webpage from scrolling to the top when clicking on an anchor with an ID

I have developed a CSS/HTML carousel that consists of 4 slides. The goal is to display the selected slide when clicking on the bottom button (a href). However, I am facing an issue where every time I click on a link, the selected slide appears as intended ...

Are side effects viewed differently in React compared to functional programming?

As I delve into the realms of learning React and functional programming simultaneously, I've noticed something intriguing. The concept of side effects appears to have a different interpretation in React compared to traditional functional programming. ...

Targeting HTML tags, styling names, and class names using CSS

In the markup below, I am trying to target three specific points using CSS. img style*=right class=media-element I attempted to use the code below, which did not work: img[style*="right"][class="media-element"] {margin-left:10px;} However, selecting t ...

Utilizing useEffect in the header component of ReactJS/Next.js: A Comprehensive Guide

In my next.js/react project, I have a component called header.js that is included on every page. Within this component, I've implemented a typewriter effect with rotation by using the following code snippet inside useEffect: export default function H ...

The button functionality gets hindered within the Bootstrap well

I'm trying to figure out what's wrong with my code. Here is the code: https://jsfiddle.net/8rhscamn/ <div class="well"> <div class="row text-center"> <div class="col-sm-1">& ...

The code encountered an error because it was unable to access the property 'style' of an undefined element on line 13 of the script

Why is it not recognizing styles and showing an error? All paths seem correct, styles and scripts are connected, but it's either not reading them at all (styles) or displaying an error. Here is the html, javascript, css code. How can this error be fix ...

What is causing some Font Awesome icons to not function properly with boostrapCDN?

I thought all Font Awesome icons would work by linking this bootstrap stylesheet, but I've only managed to get one of them (`.fa fa-deskto`) to display. The rest, like the second one for example (link below), simply don't show up: Both icons are ...

Modifying the number of stars in MUI Rating

Recently, I've been experimenting with MUI and Font Awesome. Font Awesome makes it easy to use a ternary operator to display a specific number of stars based on a rating value. For example, if an object has a rating of 4.5, it will show 4 and a half s ...

The onSubmit function in Formik fails to execute if there are no input values present

I am currently working on building a form using Next.js, TypeScript, and the Formik + Yup libraries. I've encountered two scenarios: one where an input field is visible and Formik captures the value, and another where the input is not visible and the ...

Is localStorage.getItem() method in NextJS components behaving differently?

I'm working on my nextjs application and I wanted to utilize the power of localstorage for storing important data throughout my app. Within the pages directory, specifically in the [slug].tsx file, I implemented the following logic: export default fu ...

Is it possible to combine a data type and a specific value when using PropTypes oneOf?

Can PropTypes.oneOf be used to ensure the presence of a specific type or string literal? For example: display: PropTypes.oneOf([PropTypes.bool, 'autohide']), Or does it interpret PropTypes.bool as whatever literal value it returns? I couldn&ap ...