Utilizing Pseudo Classes in Custom Styled Components with MUI

Exploring the world of React and MUI styled components for the first time. Currently, I'm delving into grid layouts and trying to style all children of a specific component. My goal is to target ${Item1}:nth-child(3n-1), ${Item2}:nth-child(3n-1), ${Item3}:nth-child(3n-1), but my approach seems to be incorrect:

const Grid = styled('div')(({ theme }) => ({
    width: '100%',
    height: '100%',
    padding: 0,
    display: 'grid',
    gap: 0,
    gridTemplateColumns: 'repeat(3,minmax(0,1fr))',
    `${Item1}:nth-child(3n-1)`: {
        backgroundColor: 'lightYellow'
    },
    gridTemplateColumns: 'repeat(3,minmax(0,1fr))',
    `${Item2}:nth-child(3n-1)`: {
        backgroundColor: 'lightGreen'
    },
    gridTemplateColumns: 'repeat(3,minmax(0,1fr))',
    `${Item3}:nth-child(3n-1)`: {
        backgroundColor: 'lightBlue'
    }
}

const Item1 = styled('div')(({ theme }) => ({
    ...
}));

const Item2 = styled('div')(({ theme }) => ({
    ...    
}));

const Item3 = styled('div')(({ theme }) => ({
    ...
}));

<Grid>
    <Item1 />
    <Item2 />
    <Item3 />

    <Item1 />
    <Item2 />
    <Item3 />

    <Item1 />
    <Item2 />
    <Item3 />
<Grid>

Answer №1

Element is the immediate offspring of Box, allowing you to use the selector div > div:

const Box = styled('div')(({ theme }) => ({
  ...,
  '& > :nth-child(3n-2)': {
    backgroundColor: 'lightYellow',
  },
  '& > :nth-child(3n-1)': {
    backgroundColor: 'lightGreen',
  },
  '& > :nth-child(3n)': {
    backgroundColor: 'lightBlue',
  },
}));

If you wish to style a specific child element, you can assign it a class name for identification:

const Box = styled('div')(({ theme }) => ({
  ...,
  '& > .element1': {
    backgroundColor: 'lightYellow',
  },
  '& > .element2': {
    backgroundColor: 'lightGreen',
  },
  '& > .element3': {
    backgroundColor: 'lightBlue',
  },
}));
<Box>
  <Element className="element1" />
  <Element className="element2" />
  <Element className="element3" />

  <Element className="element1" />
  <Element className="element2" />
  <Element className="element3" />

  <Element className="element1" />
  <Element className="element2" />
  <Element className="element3" />
</Box>

https://codesandbox.io/s/69742570-how-to-use-pseudo-select-to-specific-mui-styled-component-28x5v?file=/demo.js

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

Creating a repeated design using linear gradients in CSS

As I venture into the realm of Photoshop patterns for the first time, I am working on a webpage where I plan to incorporate these patterns to enhance the background. The pattern I have discovered measures 120x120 px. If I were to stop here, I would simpl ...

NestJs backend returning empty response to ReactJs frontend communication

My ReactJs frontend (localhost) is calling a NestJs backend: fetch("http://myappherokuapp.com/user/login", { method: "POST", mode: 'no-cors', headers: { 'Content-Type': 'appli ...

Encountering issues with React Routes overlapping when implementing an optional route for my landing page

Let me clarify the question for you, I have several routes set up like this: <Route exact path="/:city?" component={HomePage} > </Route> <Route path="/Register1" component={register1}> </Route> <Route path="/Register2" compo ...

Make the navigation bar stay at the top of the page when scrolling past another element with a top position of 100vh

Trying to explain a unique concept here. I want a nav bar fixed in the position of top:100vh, so that as I scroll down and reach the next section, the navbar sticks at the top rather than staying stuck at the beginning with position:fixed top:0. The aim is ...

Error: When attempting to utilize the Image-Slider, an issue arises with reading the property 'classList' which is undefined

I am currently in the process of developing a website using Strapi as my CMS and Next.js(React) for the frontend. The website features an image slider that includes images, headlines, and descriptions. However, I have encountered an issue where after spen ...

Interactable links (hyperlinks / mailto) embedded within text display using React Native

Is there a way to create a component that allows the text passed to it to have hyperlinks become tappable and email addresses automatically open the default mail app on the device? ...

How to make a div disappear when hovered using Tailwind CSS

I need help with my code that is not working as expected. I have a set of images displayed as cards, each with text below them. I am trying to hide the text and only show the image using Tailwind v2, but I can't seem to get it right. Here's my co ...

Achieve full width for container using flexbox styling

In an attempt to develop a category dropdown menu with multiple columns based on the length of the <ul>, I am facing some challenges. For reference, you can view the fiddle that I have created here. The goal is to arrange each submenu item below th ...

React slick does not display arrows when there are 4 or more photos

I am facing an issue where the next and previous arrows are not appearing when I have 4 or more photos on react-slick. However, they show up fine when there are 3 or fewer photos. You can view my code at this link: https://codesandbox.io/s/wyyrl6zz3l ...

Using jQuery to toggle the menu

I've been brainstorming ways to add a toggle menu on my website and finally stumbled upon a solution that works great! http://jsfiddle.net/hhcsz5cr/ <div> <h1><button class="button" data-circle="travel"> <i cl ...

CSS hover image resizing not functioning as expected

Is there a way to dynamically scale up an image when hovered over? I'm trying to achieve an effect where the image increases from 100x75 pixels to 300x225 pixels. Everything seems to be working fine with the layout, but the width doesn't seem to ...

Ant Design - Field validation triggers only upon clicking outside of the input field

I have a form with an email field that currently validates the input after each change. How can we modify it to only validate when the user clicks out of the field or submits the form? Below is an example of the form structure: return ( <Form {...l ...

Error occurs while attempting to configure

I am facing some confusion with the usage of aws-sdk in a React project. I have been trying to configure it, but encountered an error that has left me puzzled. Oddly enough, when I checked the object debugger everything seemed fine. However, as soon as I t ...

What is the best way to globally install all necessary packages and dependencies?

Every time I create a new React app, a node_modules folder is generated with numerous packages under the app/project directory. If I create multiple apps, each one will have its own node_modules folder with thousands of packages. This leads to redundant no ...

Having trouble applying CSS styles to the root element despite using a CSS file

My reactjs entry component setup looks like this: import React from "react" import ReactDOM from 'react-dom'; import App from "./js/components/App.js" import './index.css'; ReactDOM.render(<App />, document.getElementById(' ...

How to eliminate the issue of horizontal scrollbar appearing in Material UI Datagrid

I'm currently utilizing the Mui datagrid component and encountering a horizontal scrollbar issue. const columns = [ { field: 'fileName', headerName: 'File Name', flex: 2, headerClassName: 'table-header' }, { field ...

Nodejs is encountering an error while attempting to refresh pages, resulting in the inability

I recently completed a website, and I've noticed an issue where the home page refreshes just fine, but when I navigate to other pages and hit refresh, I encounter this error: Cannot GET /otherpage The website is built using react-navigation, and I su ...

What is the best way to customize column width in AG-Grid?

I am looking for a way to dynamically set column width in my table. I have provided a stackblitz example which demonstrates that when changing the screen size, only the table border adjusts, but not the column widths. Is there a way to also change the col ...

The payload is properly returned by the Reducer, however, the component is receiving it as

In my current project, I am developing an application that involves fetching data from a firebase database. This particular database does not require authentication, and I have already adjusted the access rules to allow for public access. One of the actio ...

Animate with jQuery to swap the positions of two floating divs

Hello, I recently made some updates to the code by adding 2 divs of different sizes. I am trying to achieve a switching animation using CSS floats for these divs. If you'd like to take a look at the current code, please visit - http://jsfiddle.net/jz ...