Invalid hook call. Hooks can only be called inside of the body of a function component when apply style to class base component with material-ui
material-ui makeStyles
function only works inside function components, as it uses the new React Hooks APIs inside.
You have two options:
- Convert your class component to a functional component.
- Use a Higher Order Component as in material-ui docs
I personally recommend the first approach, as this is becoming the new standard in React development. This tutorial may help you get started with functional components and check the docs for React Hooks
Use withStyles
:
App.js
:
import {withStyles} from '@material-ui/core/styles'
// ...
const styles = theme => ({
paper: {
padding: theme.spacing(2),
// ...
},
// ...
})
class App extends React.Component {
render() {
const {classes} = this.props
// ...
}
}
export default withStyles(styles)(App)
Root.js
:
import React, {Component} from 'react'
import App from './App'
import {ThemeProvider} from '@material-ui/styles'
import theme from '../theme'
export default class Root extends Component {
render() {
return (
<ThemeProvider theme={theme}>
<App/>
</ThemeProvider>
)
}
}
theme.js
:
import {createMuiTheme} from '@material-ui/core/styles'
const theme = createMuiTheme({
palette: {
primary: ...
secondary: ...
},
// ...
}
export default theme
See Theming - Material-UI.
See Higher-order component API.