Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style nested elements in react with styled-components?

Tags:

css

reactjs

I'm using styled components and would like to style a child inside a div via nested css. See my demo here

const styles = theme => ({
  root: {
    ...theme.typography.button,
    backgroundColor: theme.palette.common.white,
    padding: theme.spacing.unit,
    ">span": {
      background: "red"
    }
  }
});

function TypographyTheme(props) {
  return (
    <div className={props.classes.root}>
      <h1>
        <span>{"This div's text looks like that of a button."}</span>
      </h1>
    </div>
  );
}
like image 272
vuvu Avatar asked Jun 25 '18 11:06

vuvu


People also ask

How can you apply dynamic styles to styled-components?

One way to dynamically change css properties with styled components is to insert a custom prop into your React component and access said property using the dollar sign and curly braces commonly used for template literals. Our current example is testing to see if our use pointer prop is true.

Can you use Classnames with styled-components?

Styling any componentstyled can style any component as long as it accepts a className prop.

What is the best way to style components in React?

The most sought after way to add styling to any DOM element in React is via classes. In React, we add classes using the className attribute on the DOM elements. To give CSS properties to the class main-heading we'll use an external CSS stylesheet.

Can I use style in JSX?

Inline Styling Note: In JSX, JavaScript expressions are written inside curly braces, and since JavaScript objects also use curly braces, the styling in the example above is written inside two sets of curly braces {{}} .


1 Answers

It looks like JSS syntax, not styled component.

Change this:

const styles = theme => ({
  root: {
    ...theme.typography.button,
    backgroundColor: theme.palette.common.white,
    padding: theme.spacing.unit,
    ">span": {
      background: "red"
    }
  }
});

With this:

const styles = theme => ({
  root: {
    ...theme.typography.button,
    backgroundColor: theme.palette.common.white,
    padding: theme.spacing.unit,
    "& span": {
      background: "red"
    }
  }
});

or if you wouldn't that change all nested spans

const styles = theme => ({
  root: {
    ...theme.typography.button,
    backgroundColor: theme.palette.common.white,
    padding: theme.spacing.unit,
    "& > h1 > span": {
      background: "red"
    }
  }
});

Try this codesandbox https://codesandbox.io/s/vm3qnmj75l

For reference: http://cssinjs.org/jss-nested/

like image 72
Rizal Ibnu Avatar answered Oct 23 '22 01:10

Rizal Ibnu