Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to theme components with styled-components and Material-UI?

Is there a possibility to use the Material-UI "theme"-prop with styled-components using TypeScript?

Example Material-UI code:

const useStyles = makeStyles((theme: Theme) => ({
  root: {
    background: theme.palette.primary.main,
  },
}));

Now I want to replace this code with styled-components.
I have tested the following implementation (and other similar implementations) without success:

const Wrapper = styled.div`
  background: ${props => props.theme.palette.primary.main};
`;
like image 660
R2T8 Avatar asked Oct 16 '25 16:10

R2T8


1 Answers

You can use withTheme to inject the theme as a prop.

import React from "react";
import { withTheme } from "@material-ui/core/styles";
import styled from "styled-components";

const StyledDiv = withTheme(styled.div`
  background: ${props => props.theme.palette.primary.main};
  color: ${props => props.theme.palette.primary.contrastText};
`);
export default function App() {
  return (
    <StyledDiv>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </StyledDiv>
  );
}

Edit Use theme with styled-components

For a start on the TypeScript aspects, see this demo: https://codesandbox.io/s/xyh60

This is from the withTheme HOC portion of the documentation.

like image 129
Ryan Cogswell Avatar answered Oct 18 '25 07:10

Ryan Cogswell



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!