Exploring the usage of pseudo elements with Material UI

Is it possible to target pseudo selectors like ::before, ::after in Material UI? For instance, is it feasible to use them in a component like this?

const customStyles = makeStyles((theme) => ({
  root: {
    textAlign: 'center',
    '&::before': {
      content: '"blabla"'
    },
    '&::after': {
      content: '"blabla"'
    },
    ':before': {},
    after: {}
  }
}));

function CustomComponent(props) {
  const classes = customStyles();
  return (
    <Typography
      className={{ root: classes.root, before: classes.before, after: classes.after }}>
      {props.children}
    </Typography>
  );
}

Answer №1

Feel free to check out this sandbox project that I have created. Everything seems to be functioning correctly, but please let me know if there is anything I may have overlooked in understanding your issue.

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Typography from "@material-ui/core/Typography";

const useStyles = makeStyles(theme => ({
  root: {
    textAlign: "center",
    "&::before": {
      content: '"-"'
    },
    "&::after": {
      content: '"-"'
    }
  }
}));

export default function App(props) {
  const classes = useStyles();
  return (
    <Typography className={classes.root} {...props}>
      Hello
    </Typography>
  );
}

If you are using the className props incorrectly, make sure to pass a string rather than an object. The classes props expect an object, typically used on components with exposed class names for overriding inner styles. For instance, in the case of Typography Component, you can override the root element style like so.

export default function App(props) {
  const classes = useStyles();
  return (
    <Typography classes={{ root: classes.root }} {...props}>
      Hello
    </Typography>
  );
}

Remember, classes and classNames serve different purposes in Material-UI, although sometimes they both offer the same solution (particularly when styling the root element of a component).

I've also put together another Sandbox project demonstrating the second solution.

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

How to vertically align and center multiple divs with Flexbox programming

I have been grappling with the challenge of aligning two sets of rows vertically, each consisting of an image on one side and text on the other. While I usually use flex to achieve vertical alignment, it seems that a different approach is needed in this pa ...

I'm curious why one of my Material UI autocomplete components is displaying options with a blue background while the other isn't. Take a look at the code sandbox for more insight

UPDATE: Problem solved! I managed to find a solution and have updated my sandbox with the fix! REVISION: After some investigation, I have identified that the issue lies within this specific line of code in the autocomplete... isOptionEqualToValue={(option ...

Error: Unable to access the 'selectPage' property since it is undefined

I am experiencing an issue with my code while using React, Material-UI, and lodash. Specifically, the render method is giving me an error stating "TypeError: Cannot read property 'selectPage' of undefined": tmppage = _.map(_.range(0, th ...

Revamp MUI class names with React Material UI's innovative randomization and elimination

Can names be randomized or Mui-classNames removed? https://i.stack.imgur.com/J6A9V.png Similar to the image displayed? (All CSS class names would be jssXXX) Appreciate your assistance. ...

What about using the Material-ui snackbar component to display various alert statuses?

Greetings! I am just starting out with react and material-ui, and I'm currently experimenting with the snackbar component. I found a helpful resource about it here: https://material-ui.com/es/components/snackbars/#customized-snackbars. However, I&apos ...

Passing state from child to parent in React using the useContext hook

I'm currently working with a MetaTable Component that includes a LeftSidePanel wrapped with the UseContext. My goal is to open the panel when a button is clicked on the MetaTable (to display detailed information about a particular record). While my co ...

Prevent overflow of content and ensure text does not automatically resize when expanding

Apologies for the lengthy post, although it appears long because of the images. I aim to achieve a layout similar to this: https://i.stack.imgur.com/kuX6Tm.png To create this layout, I used the following code snippet: <?xml version="1.0" encoding="u ...

Guide to integrating Material UI v5 with Next JS v12

A new version of Material UI, MUI 5, has been released. In the previous version (MUI 4), I used to connect it by making changes in _document.js and _app.js. Is the process the same for Material UI 5? for MUI v4 _app.js import CssBaseline from '@mat ...

Issue with Material-UI Nested Checkbox causing parent DOM to not update upon selection changes

Currently, I am integrating a nested checkbox feature from a working example into my application. The functionality of the checkboxes covers seven different scenarios: - Scenario - No children, no parent selected - Select the parent -> select both pa ...

Guide to applying conditional styling to Material-UI TextField

After creating a custom MUI TextField, I implemented the following styling: const CustomDisableInput = styled(TextField)(() => ({ ".MuiInputBase-input.Mui-disabled": { WebkitTextFillColor: "#000", color: "#00 ...

What is the best way to display Material UI cards in a horizontal layout?

I'm currently incorporating Material UI into my project, Within my list of cards, I aim for them to display one after the other horizontally and then continue in the same fashion on the next row. However, they are currently stacking vertically. I&ap ...

Once the image has been observed, what steps can be taken to close it?

I wish to implement a functionality where clicking on the view button will enlarge the image, and another click on the page will return it to its original size. import * as React from 'react'; import Box from '@mui/material/Box'; imp ...

The Material Design 3 DialogFragment doesn't have the same styling as Dialogs created with MaterialAlertDialogBuilder

After migrating to Material Design 3, I've observed that DialogFragments do not have the same styling as dialogs created using MaterialAlertDialogBuilder. Is it necessary to add custom styling to DialogFragments? My assumption was that it should work ...

Maintain MUI Autocomplete in the open state even after making a selection from the

Whenever I select certain options on my Autocomplete component, I want to keep the component open. However, each time I click on onChange, the Autocomplete closes automatically and I can't seem to find a way to prevent this. Is there a workaround? In ...

Getting the first validation message from Input in React: What you need to know

When using a number input with min and max values set, I have found that if a user enters a number above the max value, I can retrieve the validation message from event.target.validationMessage during the onChange event. This functionality works well when ...

Unable to locate an image when using .find() in ReactJs

When trying to display the selected item image, only alt attributes are being displayed. In my App.js file: <Route path="/Item/:id" element={<Item />} /> This is how I styled my Link in Trending.js using MUI: <StyledLink to={& ...

What are the best locators to utilize for Python in logging into a website?

I am attempting to log in to the website. Unfortunately, I am encountering an issue with filling in my username and password. Specifically, I am having trouble with entering my username. It seems like I may be selecting the wrong class name, but I am not e ...

Unique rephrased text: "Varied wrapping styles in both

Feeling frustrated with a seemingly commonplace issue. Despite the thousands of times it has been asked before, I can't seem to find an answer on Google. I wanted to neatly display my text within one of my cards, but so far I've only achieved th ...

The MUI DataGrid Pagination has been replaced due to an error: validateDOMNesting(...): <td> should not be nested within a <div>

I'm struggling with replacing the pagination in my DataGrid component from Material-UI. Every time I try, I encounter this console error: Warning: validateDOMNesting(...): <td> cannot appear as a child of <div> I've double-checked my ...

When inputting dates manually, the KeyboardDatePicker feature is deducting one day from the selected

When using the datepicker to select a date, everything works fine. However, when manually entering a date and then saving it, the browser ends up posting a different date to the server (only referring to the date part). My time zone is UTC+03. Below is my ...