CSS pseudo selectors with MUI

ReactjsMaterial UiJss

Reactjs Problem Overview


I have seen in a lot of the MUI code that they use pseudo selectors in their react styled components. I thought I would try to do it myself and I cannot get it to work. I'm not sure what I am doing wrong or if this is even possible.

I am trying to make some CSS that will offset this element against the fixed header.

import React from 'react';
import { createStyles, WithStyles, withStyles, Typography } from '@material-ui/core';
import { TypographyProps } from '@material-ui/core/Typography';
import GithubSlugger from 'github-slugger';
import Link from './link';

const styles = () =>
  createStyles({
    h: {
      '&::before': {
        content: 'some content',
        display: 'block',
        height: 60,
        marginTop: -60
      }
    }
  });

interface Props extends WithStyles<typeof styles>, TypographyProps {
  children: string;
}

const AutolinkHeader = ({ classes, children, variant }: Props) => {
  // I have to call new slugger here otherwise on a re-render it will append a 1
  const slug = new GithubSlugger().slug(children);

  return (
    <Link to={`#${slug}`}>
      <Typography classes={{ root: classes.h }} id={slug} variant={variant} children={children} />
    </Link>
  );
};

export default withStyles(styles)(AutolinkHeader);

Reactjs Solutions


Solution 1 - Reactjs

I found out that the content attribute needed to be double quoted like this

const styles = () =>
  createStyles({
    h: {
      '&::before': {
        content: '"some content"',
        display: 'block',
        height: 60,
        marginTop: -60
      }
    }
  });

and then everything worked like expected

Solution 2 - Reactjs

As @Eran Goldin said, check the value of your content property and make sure it's set to a string "". Odds are, you are doing something like this:

'&::before': {
  content: '',
  ...
}

Which doesn't set the content property at all in the output stylesheet

.makeStyles-content-154:before {
  content: ;
  ...
}

In Material-UI style object, the content of the string is the css value, including the double quote, to fix it simply write

'&::before': {
  content: '""', // "''" will also work.
  ...
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoffView Question on Stackoverflow
Solution 1 - ReactjsJoffView Answer on Stackoverflow
Solution 2 - ReactjsNearHuscarlView Answer on Stackoverflow