user image

Jo Micheal
Published in : 2022-02-10

useStyles Invalid hook call class component

React js

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:1. You might have mismatching versions of React and the renderer (such as React DOM)2. You might be breaking the Rules of Hooks3. You might have more than one copy of React in the same appSee // for tips about how to debug and fix this problem.

When I try to use makeStyles from the Material UI in my class component it makes 

The entire component 

import React from 'react';import { Box, makeStyles, Typography } from '@material-ui/core';import Page from 'src/components/Page';import './style.css';const useStyles = makeStyles(() => ({ root: {}}));class HomeView extends React.Component { render(){ const classes = useStyles(); return ( <Page title="Homepage"> <Box p={10} class={classes.root}> <Typography variant='h1' color="textPrimary"> Hello world </Typography> </Box> </Page> ); }}export default HomeView;

How to use makeStyles with the class Component?


Mohamed Atef Date : 2022-02-10

Best answers


Best answers


You can do this using a function called withStlyes this function made for class component like the code blow 

import React from 'react';import { Box, withStyles, Typography } from '@material-ui/core';import Page from 'src/components/Page';import './style.css';const styles = ({ root: { padding: '90px' }});class HomeView extends React.Component { render(){ const { classes } = this.props; return ( <Page title="Homepage"> <Box p={10} className={classes.root}> <Typography variant='h1' color="textPrimary"> Hello world </Typography> </Box> </Page> ); }}export default withStyles(styles)(HomeView);

Please note that at the end when I exported the component class I added the function with it and passed the styles to the function so when you try to console.log(this.props); you will find that classes has been added to the component props with the styles you wrote above 
that's all Good Luck

Jo Micheal Date : 2022-02-10

Great this example works good

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

React usestate array map() is not working
Publish date: 2022-04-22 | Comments: 3

Tag: React js

[solved] Reactjs is not updating the props
Publish date: 2022-02-04 | Comments: 2

Tag: React js

How to implement SSO with React and ASP.NET Core Web API ?
Publish date: 2022-11-03 | Comments: 0

Tag: React js

React Component displaying a list of lines
Publish date: 2022-03-19 | Comments: 3

Tag: React js

import link as router link from 'react-router-dom' Reactjs
Publish date: 2021-09-30 | Comments: 3

Tag: React js

Export 'Switch' (imported as 'Switch') was not found in 'react-router-dom'
Publish date: 2022-04-02 | Comments: 2

Tag: React js