I am just started to learn reactjs using material-ui but getting this error when apply style to my component. My code:
const useStyles = makeStyles(theme => (
material-ui makeStyles
function only works inside function components, as it uses the new React Hooks APIs inside.
You have two options:
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
if you have created a functional component and still run into this issue... the next thing to look for are the dependency versions.
I tried a new stackblitz project to test a material-ui component and got this error. My dependencies were:
react 16.12
react-dom 16.12
@material-ui/core 4.9.14
So I had to change to latest react version using react@latest
and react-dom@latest
which got me to the following:
react 16.13.1
react-dom 16.13.1
@material-ui/core 4.9.14
Sharing here so that it can help other people who run into this... thanks to this post for the hint
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.