Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Material UI : 'theme' is not defined no-undef

I am creating a simple react application using material-ui. I am using MuiThemeProvider and ThemeProvider for theme.

App.js

import React from 'react';
import { createMuiTheme,  MuiThemeProvider } from '@material-ui/core/styles';
import { ThemeProvider } from '@material-ui/styles';
import { CssBaseline } from '@material-ui/core';
import { Topic } from './dashboard/components/drawer/topic.js' 

const theme = createMuiTheme({
    palette : {
        type : 'dark',
        background : {
            default : "#000000"
        },
        secondary : {
            main : '#E19A4C'
        }
    }
})

function App() {
    return (
        < MuiThemeProvider theme={theme}>
            <ThemeProvider theme={theme}>
                <CssBaseline />
                <div className="App">
                    <Dashboard />
                    <Topic />
                </div>
            </ThemeProvider>
        </ MuiThemeProvider>
    );
}

export default App;

Topic.js

import React, { Component } from 'react';
import { Typography, makeStyles, Box, Paper } from '@material-ui/core';

const style = makeStyles(theme => ({
    paper : {
        background : '#ff00ff'
    }
}))

export const Topic = (props) => {

    const classes = style()

    return (
        <div>
            <Paper className={classes.box}>
                <Typography variant="h6" component="h6" gutterBottom>
                    {props.data}
                </Typography>
            </Paper>
        </div>
    )
}

export default Topic

I am getting error Uncaught ReferenceError: theme is not defined

I have tried { withTheme : true } in makeStyles but it doesn't work.

Sending theme as props works but is not recommended. Can Someone please help?

like image 535
addy Avatar asked Nov 07 '25 22:11

addy


1 Answers

In your Topic.js file try using useTheme hook like this:

import React, { Component } from 'react';
import { Typography, makeStyles, Box, Paper } from '@material-ui/core';
import { useTheme } from '@material-ui/core/styles';

const style = makeStyles(theme => ({
    paper : {
        background : '#ff00ff'
    }
}))

export const Topic = (props) => {

    const classes = style()
    const theme = useTheme();

    return (
        <div>
            <Paper className={classes.box}>
                <Typography variant="h6" component="h6" gutterBottom>
                    {props.data}
                </Typography>
            </Paper>
        </div>
    )
}

export default Topic

Now you can access the theme you created in App.js from theme variable(e.g const theme)

like image 192
IVIosi Avatar answered Nov 09 '25 12:11

IVIosi



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!