5

There is an example of use of useTheme hook on Material-UI website: https://material-ui.com/styles/advanced/#theming

And code here:

    import React from 'react';
    import { ThemeProvider, useTheme } from '@material-ui/styles';

    function DeepChild() {
      const theme = useTheme();

      return <span>{`spacing ${theme.spacing}`}</span>;
    }

    function UseTheme() {
      return (
        <ThemeProvider
          theme={{
            spacing: '8px',
          }}
        >
          <DeepChild />
        </ThemeProvider>
      );
    }

    export default UseTheme;

But it doesn't show how to inject the theme. When I try to inject some properties with className it doesn't do anything. Code here:

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

function DeepChild() {
  const theme = useTheme();

  return <div className={theme}> eldfo elo </div>;
}

function App() {
  return (
    <ThemeProvider
      theme={{
        spacing: "40px",
        color: "yellow",
        fontSize: "30px"
      }}
    >
      <DeepChild />
    </ThemeProvider>
  );
}

export default App;

My question is how to inject it correctly?

kenodek
  • 362
  • 1
  • 2
  • 13

1 Answers1

7

Use it just like any other React hook:

function App() {
  const theme = useTheme<Theme>()
  const space = theme.spacing(1)
  return <p>Space: {space}</p>
}

Note that what you get is the full theme. If you want to get any class name, you should use theme.className but you did not define a className property in your theme example.

What you want to do is probably:

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

function DeepChild() {
  const theme = useTheme();

  return <div className={theme.divClass}> eldfo elo </div>;
}

function App() {
  return (
    <ThemeProvider
      theme={{
        divClass: {
          spacing: "40px",
          color: "yellow",
          fontSize: "30px"
        }
      }}
    >
      <DeepChild />
    </ThemeProvider>
  );
}

export default App;
Stéphane Veyret
  • 1,791
  • 1
  • 8
  • 15
  • didnt work for me. sandbox with code.. plz can you help sharing a working example. https://codesandbox.io/s/material-demo-vmsp2?file=/demo.js – saurabh Apr 09 '20 at 07:14