Utilizing reusable styled components with pseudo elements and advanced logic

How can I make the shared style more dynamic by changing the value of left or width based on a passed value or boolean logic across different components?

I prefer not to pass it as a prop in the actual component like

<bar left="20" />
, but rather have it declared within the styles.

const dynamicSharedStyle = css`
  ::after {
    content: '';
    left: 0;
    width: 100%;
    ${(props) => props.beta && 
    `
      top: 0;
    `
  }
`

const fooComponent = styled.div`
  ${dynamicSharedStyle}
`

const barComponent = styled.div`
  ${dynamicSharedStyle}

  ${childElement} {
     ${dynamicSharedStyle}
  }
`

Answer №1

Optimize your code by using a function instead:

const getShared = (props) => css`
  ::after {
    content: '';
    left: ${props.left || '0'};
    width: ${props.width || '100%'};
    ${(otherProps) => otherProps.beta && 
    `
      top: 0;
    `
  }
`

const foo = styled.div`
  ${(props) => getShared(props)}
`

const bar = styled.div`
  ${(props) => getShared(props)}

  ${child} {
    ${(props) => getShared(props)}
  }
`

If you need to override shared CSS easily, here's a simple example:

<div>
      {/* this is a div that applies shared CSS */}
      <div css={shared}>this is shared css</div>

      {/* this is a div that extends the shared CSS in its styling */}
      <FirstContainer>container extending shared css</FirstContainer>

      {/* this is a div that uses shared CSS in its styling but overrides border color using a prop*/}
      <SecondContainer borderColor="red">container overriding the shared css</SecondContainer>
 </div>

Check out the associated styling below:

// this represents the shared CSS
export const shared = css`
    width: 100px;
    height: 100px;
    border: solid 1px green;
    margin: 40px;
`

// div applying the shared CSS
export const FirstContainer = styled.div`
    ${shared}
`

// div utilizing the shared CSS while also changing the border color
// props retrieve all properties passed to the SecondContainer component (similar to left in the bar component)
export const SecondContainer = styled.div`
    ${shared}

    border-color: ${(props) => props.borderColor}
`

This is how it will look like:

https://i.stack.imgur.com/Wuc02.png

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

Run a PHP function using <button onclick=""> tag

Is it possible to trigger the execution of a PHP script when clicking an HTML button? I am aware that simply calling a PHP function directly from the button's onclick event like this: <button onclick="myPhpFunction("testString")">Button</butt ...

You need to include getStaticPaths for dynamic SSG pages or else it will be missing in the address

Currently, I am working on an online shop project utilizing a fake API. My objective is to display a list of lots belonging to each category. To achieve this, I have a category component that should navigate to the lotsInCategory page (lotsInCategory/[cate ...

What is the best way to align inline-block elements in the center?

I'm looking for a way to center inline-block elements, but I haven't had much luck so far. When I tried using margin-top: x em;, it just moved the image down instead of centering it. The inline-block is intentionally nested inside an image block. ...

The Map function is not functioning properly for a Next.js application that is relying on

I'm encountering an issue when attempting to display a simple JSX component based on Firebase data. When I try to return the component individually, it works perfectly fine. However, when I attempt to map over the data and display multiple components, ...

Tips for creating consistent background text size

i need assistance creating a box for text that looks like this https://i.stack.imgur.com/JOC0r.png my CSS code for the box is as follows: .bg-text-kol2 { background-color: #ffffff; background-size: 10px 10px; border-top-left-radius: 10px; border ...

Animating component transitions using react-router

Currently working with React and react-router, I have page-like components that I want to implement two phase transition animations for when the main view of the application changes. When a <Link> is clicked The old (current) view fades out (co ...

Adjust the background color of the date and time selection tool

Trying to customize the background of a datetime picker created using jquery.pttimeselect.js. Despite linking the correct css file (jquery.pttimeselect.css), I am unable to change the background color. Any suggestions on how to successfully modify the ba ...

Struggling with getting the JavaScript, scss, and CSS television animation to turn on and off properly? Seeking assistance to troubleshoot this

After finding this javascript code on Codepen and seeing that it worked perfectly in the console there, I tried to run it on my computer with jQuery but it didn't work outside of Codepen. Even when attempting to use it on JSfiddle or compile the SCSS ...

What is the process for configuring text on an md-Switch?

I need help setting informational text on an md-switch element from Angular Material design. I want the user to be able to easily understand the current state of a field value. Here is a visual example of what I'm trying to achieve: Can someone guide ...

"An issue with the rc-tooltip causing flickering when it is positioned too close to the edge of the window

I've come across a problem with the rc-tooltip package where the tooltip flickers when it appears too close to the edge of the window. It seems to struggle to decide where to position itself, especially when set to top/bottom and there is limited spac ...

Instructions for correctly integrating the ng2-datepicker module into an Angular 2 application

Ng2-datepicker (1.0.6) Angular2 (2.0.0-rc.5) As I attempted to implement it in my HTML following the documentation, I encountered the following error: zone.js:484 Unhandled Promise rejection: Template parse errors: Can't bind to 'ngMode ...

"Interactive User Interface: Material Design inspired React cards with pop-up mod

Currently, I am working on configuring a React JS / Material UI modal dialog feature in my project. The goal is to make it so that when a user clicks on a card, a corresponding full-sized image with title and subtitle pops up. Each card's data is fetc ...

Transmitting information from JavaScript to PHP server results in receiving a 500 Error

I have been exploring various code examples and techniques to transmit data from my website to the server's database. After evaluating different options, I concluded that making an ajax call to send the data would be the most efficient method. Here i ...

What is the best way to connect my React application to my Express/MongoDB backend using a proxy?

I am struggling to comprehend why the API I developed in MongoDB and Express is resulting in an error message of net::ERR_CONNECTION_REFUSED. To challenge myself, I chose to include my own backend using Node, Express, and MongoDB in a simple app created w ...

The Next.js API is indicating that the API request was resolved without a response being sent, however, I am confident that I

After creating a basic page and API for uploading a CSV file, I encountered an issue. The file uploads successfully and gets saved on the server through the API, but an error message pops up: API resolved without sending a response for /api/uploadv2, this ...

DerivedStateFromProps function does not execute

Incorporating React version 16.3.1 along with next.js, I have embedded the method getDerivedStateFromProps within a class that extends PureComponent. Here is an excerpt of the code: Header.js import { PureComponent } from 'react' ... expor ...

CSS - Radio buttons featuring closely spaced circular options

I am attempting to create small circles that act like radio buttons without any spacing between them. I was successful in achieving this, but I ran into issues with removing the space between the circles. The margin between two circles should be limited to ...

The uncomplicated bar graph and its corresponding axis line up perfectly beside each other in an SVG diagram

I'm currently working on a stacked bar chart in my CodePen project found here: https://codepen.io/a166617/pen/qBXvzQd However, I am facing an issue where the graph is not aligned properly with the x-axis and y-axis lines. The barchart seems to be sli ...

Having trouble with less.modifyVars not functioning properly in Visual Studio?

I attempted to dynamically change the LESS variable using HTML within an AngularJS function. The code worked fine on XAMPP with simple HTML and CSS, but when I transferred it to an enterprise app in Visual Studio, it stopped functioning properly. While the ...

Setting a CSS Variable with the Help of jQuery

I need help with changing the background color of a specific .div element when it is clicked on. I want the color to be a variable that can be changed by the user, and this change should occur when the document is ready. Currently, I am using a CSS variab ...