Gal Grünfeld
Gal Grünfeld

Reputation: 840

Material-UI | Using `theme` in makeStyles

I'm trying to take an muiTheme, pass it down to a component via ThemeProvider and to its children, and then use the theme's properties in both of them in a classes object that's created by makeStyles.

Specifically, these are the components/files I have:

What I want to do is do add a classes object created by makeStyles() in each of the components, and each of them use the theme's properties. I'm not posting code here because I tried a lot of combinations of the functions and I suppose that I just have a hole in my understanding of how some of those functions work.

So here's a reproduction without any classes: LeftSection and RightSection rendering Subsection with their themes - to this I want to add classes.

Here is the code of the Subsection component where I want to use classes:

import React from "react";
import { useTheme } from "@material-ui/styles";

function Subsection(props) {
  const theme = useTheme();
  return (
    <p
      style={{
        color: theme.palette.primary.main
      }}
    >
      test
    </p>
  );
}

export default Subsection;

How can I do that?

Upvotes: 7

Views: 7453

Answers (1)

Ryan Cogswell
Ryan Cogswell

Reputation: 80986

Below is the syntax for using classes which use the theme for this styling:

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

const useStyles = makeStyles(theme => ({
  paragraph: {
    color: theme.palette.primary.main
  }
}));
function Subsection(props) {
  const classes = useStyles();
  return <p className={classes.paragraph}>test</p>;
}

export default Subsection;

Edit serene-pond-t07i1

Without seeing the code of what you have tried before, it is hard for me to know what specific holes you may have in your understanding, so if you have specific questions about this I can add some more explanation/references.

Upvotes: 14

Related Questions