Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherit CSS classes in styled-components definitions?

I want to style my app using styled-components where my components inherit styles from existing globally defined CSS. In the example below, how can I make Surface inherit the classes .raised and .bordered so that I don't have to repeat className="raised bordered" in each usage? I want something similar to Composition in Emotion.

https://codesandbox.io/s/optimistic-ramanujan-xs8rt

App.js

import "./styles.css";
import styled from "styled-components";

const App = () => (
  <div>
    <Surface className="raised bordered">Hello World 1</Surface>
    <Surface className="raised bordered">Hello World 2</Surface>
    <Surface className="raised bordered">Hello World 3</Surface>
  </div>
);

const Surface = styled.div`
  color: darkblue;
  margin: 20px;
`;

export default App;

styles.css

.raised {
  box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
}

.bordered {
  border: 1px solid black;
}
like image 504
pyjamas Avatar asked Mar 11 '26 18:03

pyjamas


2 Answers

This is doable using attrs as shown below

import "./styles.css";
import styled from "styled-components";

const App = () => (
  <>
    <Surface>Hello World 1</Surface>
    <Surface>Hello World 2</Surface>
    <Surface>Hello World 3</Surface>
  </>
);

const Surface = styled.div.attrs({
  className: "raised bordered"
})`
  color: darkblue;
  margin: 20px;
`;

export default App;
like image 118
pyjamas Avatar answered Mar 13 '26 08:03

pyjamas


If i'm right understood, you want customize component without external css and use it anywhere in the project. Easiest way use is props. second more complex create for each .raised and .bordered it's own styles components. easiest way example

App.js

import { Surface } from "./Surface";

const App = () => (
  <div>
    <Surface bordered>Hello World 1</Surface>
    <Surface boxShadow>Hello World 2</Surface>
    <Surface bordered boxShadow>
      Hello World 3
    </Surface>
  </div>
);

export default App;

Surface.js

import styled from "styled-components";

const SurfaceStyle = styled.div`
  color: darkblue;
  margin: 20px;
  ${({ bordered }) => bordered && "border: 1px solid black"};
  ${({ boxShadow }) =>
    boxShadow && "box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;"}
`;

export const Surface = ({ bordered, boxShadow, children }) => {
  return (
    <SurfaceStyle bordered={bordered} boxShadow={boxShadow}>
      {children}
    </SurfaceStyle>
  );
};
like image 37
Anton Avatar answered Mar 13 '26 08:03

Anton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!