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

Interactive sidebar scrolling feature linked with the main content area

I am working with a layout that uses flexboxes for structure. Both the fixed sidebar and main container have scroll functionality. However, I have encountered an issue where scrolling in the sidebar causes the scroll in the main container to activate whe ...

Changing the CSS of ng-view when triggering CSS in ng-include: A step-by-step guide

Incorporating my left-hand, vertical navbar into the page using ng-include, I've managed to make it expand right on hover. Each page is enclosed within a <div class="wrapper">. My goal is to adjust the margin of each wrapper as the navbar expan ...

Stopping the sound when its' Div is hovered over

I've managed to successfully trigger the audio to play on hover, but I'm having trouble getting it to pause when my mouse leaves the area. Check out the code in action here: https://jsfiddle.net/jzhang172/nLm9bxnw/1/ $(document).ready(functio ...

Next.js: 404 Error Occurs When Accessing Images Post-Build

The standard URL structure is http://localhost:5000/_next/image?url="someURL". I'd like the URL format to be http://localhost:5000/demo/_next/image?url="someURL". This can be achieved using the following code snippet: // next.con ...

<a> slightly off-centered horizontal alignment

I've been trying to center a link using different methods like text-align:center and display:inline-block, but it seems to be slightly off-center. I've attached images along with my code below for reference. Any assistance would be greatly apprec ...

What could be causing my button to be elongated in a vertical direction when a logo image is present

I am currently utilizing tailwindcss for my project. Within a flexbox container, I have placed a login button which appears to be stretched out. <nav font-am class="m-6 text-xl"> <div class="flex flex-row justify-between conta ...

A recurring issue is causing the state variables in React to reset to their default values due to the

I'm currently working on retrieving values (let's call it X) from my database and showcasing a new random number within the range of (X+2) to (X-2) every 3 seconds. Default Values: //in Reducer (Initial State) cprice : { "available":50, ...

Issue with importing subscriptions in Next.js using urql library

I'm having trouble getting urql subscriptions to function correctly in my NextJS project due to import issues. The problem arises when I try to use the recommended graphql-ws library in urql, which requires a ws implementation library (e.g. 'ws& ...

Styles and CSS have been successfully loaded, however, the content is not appearing

After attempting to import a web HTML CSS template into my self-made MVC, I encountered an issue. While the template works properly on its own, it fails to connect to the CSS files and display proper styles when accessed through my controller. Instead, onl ...

I'm wondering why my second div is displaying a different size compared to the rest, even though they all share the same container-fluid class

Within the HTML snippet provided, utilizing Bootstrap, all three child divs possess the container-fluid class. However, why does the 2nd div differ from the others? Refer to this example Div Example. Div1 and div4 exhibit the same characteristics, as do d ...

Adjusting the default TextField hint alignment - MaterialUI

As I delved into using material UI, I encountered a challenge with the TextField component. While the default animation was aesthetically pleasing, I desired to center align it instead of it remaining stuck in the top left corner: https://i.stack.imgur.co ...

Encountering a 500 (Internal Server Error) when sending an Axios POST request in ReactJS using Laravel Sanctum

I am a beginner in working with ReactJs and Laravel. My current issue involves trying to register a new user from the frontend to the backend, which is built on Laravel. I have implemented laravel/sanctum for creating a Single Page Application website. The ...

Order of Actions not being Dispatched by Redux Thunk

Using redux thunk presents a challenge for me. When I dispatch uploadClientImage, it creates an image object in the database and returns the image id. I require both image ids before creating client_info. The issue arises when the axios post to clients i ...

Experiencing an issue where the canvas element fails to render on mobile Chrome browser,

I've encountered an issue with a script that draws a canvas based on the background color of an image. The image is loaded dynamically from a database using PHP. The responsive functionality works fine on mobile Safari, but not on Chrome. When the re ...

Ways to dynamically eliminate focus around text inputs

I have created an HTML page and here is the link to it: My main goal is to remove the black border around the text input on this page. The challenge I am facing is that the 'things to do' list is generated dynamically, meaning it is empty when t ...

When hovering over the sidebar, it smoothly slides out. (ideally using only CSS)

I've been spending my free time working on a website, but I'm struggling to figure out how to create a navigation similar to the one featured on FontShop's site: . I want it so that when you hover over their logo (or in my case, a blank rect ...

Limiting MUI Autocomplete: Ensuring it does not open upon focus, but only upon input modification

Is there a way to prevent the Autocomplete suggestions from opening immediately when the user clicks? I only want it to open when the user starts typing. I haven't found a prop that can help achieve this. Any ideas on using onInputChange to toggle the ...

The installation of the React App was unsuccessful due to an error during installation

node --version => 14.5.0 npm --version => 6.14.6 create-react-app --version => 3.4.1 yarn --version => 1.22.4 I have exhausted all possible solutions to address this issue but unfortunately, none of them have been successful. I have reinstalle ...

Why isn't the parent div stretching alongside its child divs?

Take a look at this example: wthdesign.net/website/olaf&co/index.php I am currently working on creating a responsive layout, but I am struggling to figure out how to make the "#content" div stretch with its child div when there is more content than ex ...

The implementation of useState delays the application of dynamic styling

I'm currently developing a Next.js application. Here is the code snippet from my client-side component: const [view, setView] = useState<string[]>(["all"]); const story = stories?.holidays; const joke = stories?.jokes; const idiom = s ...