Amirreza
Amirreza

Reputation: 463

react says Error: Invalid hook call when I try to use material makestyles

I'm new to react and I'm trying to using makestyles and this is how :

in Header.jsx :

import React from "react";
import UseStyles from "./Header_style";
function Header() {
  const classes =UseStyles();
  return (
    <div className={"Main-Header"}>
      <div className={"Header-Logo"}>
        <div className={classes.test}>test</div>
      </div>
    </div>
  );
};

export default Header;

and style.js :

import {makeStyles} from '@material-ui/styles';
const UseStyles = makeStyles(theme=>({
    test: {
        backgroundColor: '#BDC3C7',
        color :'red !important',
        widtH : '18%'
    },

    }));
export default UseStyles;

but I'm getting folwing error: ×

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:

*edit: This is how I'm using Header :

import React, { Component } from 'react'
import Header from './component/heder/Header.jsx';

class App extends Component {
    constructor() {
        super();

        this.state = {
            monsters: [],
            searchField: ''
        };
    }
    render() {
        return (
            <Header/>
        );
      }
}


export default App;

and another thing, I'm getting following error too : error

Upvotes: 3

Views: 1261

Answers (2)

Amirreza
Amirreza

Reputation: 463

everybody, I've found the solution!

have to use withStyles.

Upvotes: 2

sloont
sloont

Reputation: 204

When you place your Header component in the return or render of a parent component make sure you use <Header /> and not {Header}

additionally if that's not the problem you can check this link which is the official react thread on that error.

Also posting how you render the component that is throwing the error would be very helpful.

Edit* Additionally you don't need to call makeStyles with a function. Since you are not using the theme, you can just call makeStyles with an object like this

const useStyles = makeStyles({
   test: {
     background: 'white',
     width: '100%'
   }
});

EDIT and additional answers:

Here's a snippet from MUI's official page on styles:

Difference in makeStyles imports

The way you import makeStyles:

import { makeStyles } from '@material-ui/styles

If you import this way you have to have applied the @material-ui/styles module.

If instead in your package.json you use '@material-ui/core and haven't installed @material-ui/styles you could be getting that error because you don't have the module @material-ui/styles.

If you just have @material-ui/core you can still import makeStyles without installing the standalone @material-ui/styles it is all included in @material-ui/core.

Simply import it like this instead: import { makeStyles } from '@material-ui/core/styles'

Upvotes: 3

Related Questions