Applying Material UI class in React: Troubleshooting an error with your hook call

Recently, I have started using React and encountered an issue with a hook call. I understand the root cause of the problem but unsure how to resolve it without starting from scratch. Here is the snippet of the code:

import { Fragment, PureComponent } from "react";

//Test Imports
import { Input, makeStyles } from '@material-ui/core';
import Paper from '@material-ui/core/Paper';
import Grid from '@material-ui/core/Grid';
import testDaten from './testData.js';
import { Link } from "react-router-dom";
//

 //Test
 const UseStyles = makeStyles((theme) => ({
    root: {
      flexGrow: 1,
      marginTop: '100px',
      marginLeft: '100px',
      marginRight: '50px',
      
    },
  
    grid: {
      color: theme.palette.text.primary,
    },
    paper: {
      padding: theme.spacing(2),
      textAlign: 'center',
      color: theme.palette.text.primary,
    },
    photo: {
      height: '200px',
      width: '200px',
    }
    }));
    //

class Select extends PureComponent {

    state = {
      options: [
        {
          name: 'Select…',
          value: null,
        },
        {
          name: 'A',
          value: 'a',
        },
        {
          name: 'B',
          value: 'b',
        },
        {
          name: 'C',
          value: 'c',
        },
      ],
      value: '?',
    };
  
    handleChange = (event: any) => {
      this.setState({ value: event.target.value });
    };
       
    render() {

   

    const { options, value } = this.state;
    const classes = UseStyles();

        return (
          <Fragment>
            <select onChange={this.handleChange} value={value}>
              {options.map(item => (
                <option key={item.value} value={String(item.value)}>
                  {item.name}
                </option>
              ))}
            </select>
            <h1>Favorite letter: {value}</h1>
            
            {testDaten.map((item, key) => {
            if(value != null){
            return (
            <Grid item xs={4} sm={4} key={item.id}>
              <Input value={item.id} type="number" id="idTest"/> 
              <Paper className={classes.paper}> Visitor ID: {item.id} </Paper>
              <Paper className={classes.paper}> Name: {item.firstName} {item.lastName}</Paper>
              <Paper className={classes.paper}> Type of Evidence: {item.evidenceType} </Paper> 
              <Paper className={classes.paper}>   <Link to={`/toAssessTest/${item.id}`}>More information</Link> </Paper> 
            </Grid>
          )
        }
          })}
          </Fragment>

          
        );
      }
    }

    export default Select;

I am facing a hook error within the render function due to const classes = UseStyles(); --> as far as I understand, this happens because it's not at the top level. However, I'm not sure how to apply Material UI classes without it. Any assistance on this matter would be greatly appreciated.

Thank you!

Answer №1

Transform class into a functional component or utilize Hoc(withstyles) from materialui

The code below has been converted to use withstyles to access styles from classes props

import { Fragment } from "react";
import { Input, withStyles } from "@material-ui/core";
import Paper from "@material-ui/core/Paper";
import Grid from "@material-ui/core/Grid";
import testDaten from "./testData.js";
import { Link } from "react-router-dom";

const styles = (theme) => ({
  root: {
    flexGrow: 1,
    marginTop: "100px",
    marginLeft: "100px",
    marginRight: "50px",
  },

  grid: {
    color: theme.palette.text.primary,
  },
  paper: {
    padding: theme.spacing(2),
    textAlign: "center",
    color: theme.palette.text.primary,
  },
  photo: {
    height: "200px",
    width: "200px",
  },
});

const Select = ({ classes }) => {
  const [options, setOptions] = useState([
      {
        name: "Select…",
        value: null,
      },
      {
        name: "A",
        value: "a",
      },
      {
        name: "B",
        value: "b",
      },
      {
        name: "C",
        value: "c",
      },
    ]);
    
  const [value, setValue] = useState("?");

  const handleChange = (event: any) => {
    setValue(event.target.value);
  };

  return (
    <Fragment>
      <select onChange={handleChange} value={value}>
        {options.map((item) => (
          <option key={item.value} value={String(item.value)}>
            {item.name}
          </option>
        ))}
      </select>
      <h1>Favorite letter: {value}</h1>

      {testDaten.map((item, key) => {
        if (value != null) {
          return (
            <Grid item xs={4} sm={4} key={item.id}>
              <Input value={item.id} type="number" id="idTest" />
              <Paper className={classes.paper}>
                {" "}
                Besucher-Id: {item.id}{" "}
              </Paper>
              <Paper className={classes.paper}>
                {" "}
                Name: {item.vorname} {item.nachname}
              </Paper>
              <Paper className={classes.paper}>
                {" "}
                Nachweisart: {item.nachweisart}{" "}
              </Paper>
              <Paper className={classes.paper}>
                {" "}
                <Link to={`/zuBewertenderTest/${item.id}`}>
                  More Information
                </Link>{" "}
              </Paper>
            </Grid>
          );
        }
      })}
    </Fragment>
  );
};

export default withStyles(styles)(Select);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

To continue receiving rxjs updates, kindly subscribe if the specified condition is met

Is there a way to check a condition before subscribing within the operator chain? Here's what I have: // parentElem:boolean = false; // the parent elem show/hide; let parentElem = false; // inside the ngAfterViewInit(); this.myForm.get('grandPa ...

Unable to find module 'child_process'

Here is the content of my main.ts file: import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { environment } from './environments/environment'; if ...

Tips for creating a personalized asynchronous Express handler that seamlessly receives specific typed parameters

In my quest to create a unique Express endpoint wrapper, I aim to wrap async functions and handle errors effectively. The current implementation is basic but functional: import type {Request, RequestHandler, Response} from 'express'; type Handle ...

Can you explain the significance of using curly braces in an import statement?

The TypeScript handbook has a section on Shorthand Ambient Modules, where an import statement is shown as: import x, {y} from "hot-new-module"; It doesn't explain why y is in curly braces in the above statement. If both x and y were inside the brace ...

Unable to implement new ecmascript decorators within typescript version 2.4.2

Check out this example code: function enumerable(value: boolean) { return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { descriptor.enumerable = value; }; } class A { @enumerable(false) a: number = 1 b: number ...

After the installation of Storybook, there is a duplicate identifier error that arises with 'LibraryManagedAttributes'

Upon running the command npx storybook@latest init for setting up Storybook, which results in modifying package.json, I encounter an issue where I cannot run the project using npm due to: Error: node_modules/@types/react-dom/node_modules/@types/re ...

Attempting to map an object, however it is showing an error stating that the property 'title' does not exist on type 'never'

While attempting to retrieve data from the Bloomberg API, I encountered an issue when trying to extract the title from the response object. The error message received was: Property 'title' does not exist on type 'never'. Below is the co ...

typescript - instantiate an object using values stored in an array

Assume we have a model defined as follows. export interface Basicdata { materialnumber: number; type: string; materialclass: string; } We also have an array containing values that correspond directly to the Basicdata model in order, like this: ...

The outcome from using Array.reduce may not always match the expected result

After discovering an unexpected behavior in Typescript's type-inference, I suspect there may be a bug. Imagine having a list of the MyItem interface. interface MyItem { id?: string; value: string; } const myItemList: MyItem[] = []; It's ...

Toggle the highlighting in React

I have a list of data that displays in a Collapse, and I want it to highlight for every user click in the list, but only one at a time should be highlighted. If you'd like to see a sample to better understand this concept, please check out: https:// ...

Exporting a Typescript class from one module and importing it into another module

I am encountering issues with my source tree structure, as outlined below: /project/ |- src/ |- moduleA |- index.ts |- classA.ts (which includes a public function called doSomething()) |- moduleB |- classB.ts Th ...

Jest test encounters an error due to an unexpected token, looking for a semicolon

I've been working on a Node project that utilizes Typescript and Jest. Here's the current project structure I have: https://i.stack.imgur.com/TFgdQ.png Along with this tsconfig.json file "compilerOptions": { "target": "ES2017", "modu ...

What is the best way to transfer data from Material UI to Formik?

I'm facing an issue when trying to integrate a Material UI 'Select' component into my Formik form. It seems like I am unable to pass the selected values from the Material UI component to Formik's initialValues. const [selectedHours, se ...

What is the best way to include a variable or literal as a value in styled components?

When it comes to managing various use cases, I always rely on props. However, I am currently facing a challenge in changing the border color of a styled input during its focus state. Is there a way to utilize props for this specific scenario? Despite my f ...

What is the process for implementing custom color props with Material-UI v5 in a React TypeScript project?

Looking to enhance the MUI Button component by adding custom color props values? I tried following a guide at , but encountered errors when trying to implement it in a custom component. The custom properties created in createPalette.d.ts did not work as ex ...

Can a Material UI Select element be made unresponsive to hover effects?

When a user hovers over an element, I want to achieve the following functionality: document.getElementById("dropdownCategory").disabled = true; <Tooltip arrow placement="right" title={props.description} > <FormControl id="dro ...

Using TypeScript for Routing in Angular

I encountered an error message that says the module 'route' is not available. I'm not sure why this is happening, any thoughts? "Uncaught Error: [$injector:nomod] Module 'route' is not available! You either misspelled the module n ...

Encountering an issue with MUI x-data-grid: "Module '../InputBase' not found"

The code snippets used in the project are: import React from "./testDetails.css" import { DataGrid, GridToolbar } from "@mui/x-data-grid"; import { useParams } from "react-router-dom"; import { useState, useEffect } from &quo ...

Running out of memory due to inefficient mark-compacting processes nearing the heap limit in Angular 8 allocation

A significant portion of the modules are built, with only one active in progress. The process is located at ...\src\index.js??extracted!D:\Clients\app\node_modules\sass-loader\lib\loader.js??ref--15-3!D:\src&bso ...

Yep, implementing conditional logic with the `when` keyword and radio buttons

I seem to be encountering an issue with my implementation (probably something trivial). I am utilizing React Hook Form along with Yup and attempting to establish a condition based on the selection of a radio group. The scenario is as follows: if the first ...