Encountering an error in React when attempting to convert a class component to a function

As I've been converting my class components to functions, I encountered a hook error related to my export default. Although I believe it's a simple issue, I can't seem to find the solution I need.

The following code is where the error occurs:

import React from 'react'
import {AppBar, Toolbar, Button, Typography, makeStyles} from '@material-ui/core'
import { connect } from 'react-redux'
import { Link } from 'react-router-dom'
import Menu from './Menu'

const useStyles = makeStyles((theme) => ({
    header: {
        backgroundColor: "#1d3834",

    },
    root: {
      flexGrow: 1,
    },
    menuButton: {
      marginRight: theme.spacing(2),
    },
    title: {
      flexGrow: 1,
    },
  }))

function Header(props) {
    const classes = useStyles()

    const renderContent = () => {
        switch (props.auth) {
            case null:
                return
            case false:
                return (                  
                    <Button color="inherit" href="/signin">Sign In</Button>
                )
            default: 
                return  (
                    <Button color="inherit" href="/api/logout">Sign Out</Button>
                )
        }
    }
    
     return(
        <div className={classes.root}>
        <AppBar position="static" className={classes.header}>
            <Toolbar>
            <Menu/>
            <Typography variant="h6" className={classes.title} >
            <Link 
                to={props.auth ? '/items' : '/'} 
                className="left brand-logo"
            >
                
            </Link>
            </Typography>
                {renderContent()}
            </Toolbar>
        </AppBar>   
        </div>    
     );
    
}

function mapStateToProps({auth}) {
    return{ auth }
}

export default connect(mapStateToProps)(makeStyles(useStyles) (Header))

If anyone has encountered a similar issue in the past and could provide some guidance, I would greatly appreciate it. Thanks for your help!

Answer №1

The primary concern lies in the way you export your component. Consider using the following approach instead:

export default connect(mapStateToProps)(Header)

You can omit the makeStyles(useStyles) part altogether.


+1 additional suggestion - unrelated to the original question:

This suggestion doesn't directly address your initial query, but it involves a minor enhancement in how I prefer organizing makeStyles declarations within my codebase when working with Material-UI.

I typically create a separate styles.tsx file next to the component file containing the following structure:

import { makeStyles } from "@material-ui/core"

const useStyles = makeStyles((theme) => ({
    header: {
        backgroundColor: "#1d3834",
    },
    root: {
      flexGrow: 1,
    },
    menuButton: {
      marginRight: theme.spacing(2),
    },
    title: {
      flexGrow: 1,
    },
}))

export default useStyles

Then, simply import the styles in your component like this:

import useStyles from "./styles"

And use them within your component as follows:

function Header(props) {
    const classes = useStyles()

    // ... continued implementation of your component
}

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

Recording audio with Next JS is a breeze

I'm currently working on incorporating audio recording into my Next JS app and could use some guidance. I found a helpful resource at: https://blog.logrocket.com/how-to-create-video-audio-recorder-react/ At this stage, I have the following code snipp ...

Methods for breaking down a number into individual elements within an array

Suppose there is a number given: let num = 969 The goal is to separate this number into an array of digits. The first two techniques fail, but the third one succeeds. What makes the third method different from the first two? num + ''.split(&ap ...

Vue.js enhances user input interactions

CSS <span :style="{ display : displayTitle }" @click="toggleInput()"> {{ text }} </span> <input v-if="isEditing" type="text" v-model="text" @blur="hideInput" @keydown.enter="saveChanges" @keydown.esc="cancelE ...

What is the functionality behind a free hosting website?

Is anyone familiar with websites like Hostinghood, where users can create a subdomain and upload HTML, CSS, etc.? I'm curious about how they operate and how I can create a similar site. This is my first question here, so please respond instead of disl ...

Prevent the risk of revealing your LinkedIn API key within HTML code

For my website, I am looking to incorporate the Sign In With LinkedIn feature for user logins. The initial example snippet provided in the LinkedIn API docs is as follows: <script type="text/javascript" src="//platform.linkedin.com/in.js"> api_k ...

Adjust the height of the drawer in material-ui

In my current project using react and material-ui, I am facing a simple issue that has me stumped. I am trying to create a drawer with a specific height so that it does not overlap the app bar when opened. Unfortunately, there is no built-in parameter in ...

Using ReactJS with Material UI and applying styles with withStyles including themes in TypeScript

I've been working on converting the Material UI Dashboard into TypeScript. You can find the original code here: Material UI Dashboard One issue I'm encountering is that I am unable to define CSS styles within the withStyles function while export ...

The 'export '__platform_browser_private__' could not be located within the '@angular/platform-browser' module

I have encountered an issue while developing an angular application. Upon running ng serve, I am receiving the following error in ERROR in ./node_modules/@angular/http/src/backends/xhr_backend.js 204:40-68: "export 'platform_browser_private' w ...

Highcharts: single point muted and not easily seen when markers are turned off

Highchart displaying data with some null points (only visible via tooltip if marker disabled): https://i.stack.imgur.com/u04v1.png https://i.stack.imgur.com/uRtob.png Enabling markers will resolve the issue of invisible points, but it may look cluttered ...

Tips for deactivating a single edit button

Is there a way to make it so that when I click on a checkbox, only that specific todo's edit button is disabled? Currently, clicking on a checkbox disables all edit buttons in the todo list. Any suggestions? class App extends Component { state ...

The Google analytics script encountered issues loading on a page, resulting in a 500 error code

Encountering a persistent issue where the Google Analytics script fails to load with a 500 error code on the website, but interestingly works fine when opened in a new tab. After testing on MacOS BigSur using Chrome, Firefox, and Safari in both normal and ...

What is the best way to extract a value from a JSON object?

I am having trouble deleting data from both the table and database using multiple select. When I try to delete, it only removes the first row that is selected. To get the necessary ID for the WHERE condition in my SQL query, I used Firebug and found this P ...

Explore three stylish ways to showcase dynamic JavaScript content using CSS

Objective: For Value 1, the CSS class should be badge-primary For Value 2, the CSS class should be badge-secondary For all other values, use the CSS class badge-danger This functionality is implemented in the handleChange function. Issue: Current ...

Get multiple documents when using Next.js with Firebase - Why is getDocs() only retrieving the

I'm in need of the complete collection. The issue I'm facing is that the places variable is only fetching the first document. Any assistance on this matter would be greatly appreciated. import { app, auth } from '../firebase' import { g ...

Is the 'wait > remaining' condition ever satisfied in the throttle function of underscore.js?

Check out the library code at line 860: https://github.com/jashkenas/underscore/blob/master/underscore.js if (remaining <= 0 || remaining > wait) Under what circumstance would the second part of this statement be true? Background - This is my firs ...

What is the best way to set the keyframes CSS value for an element to 0%?

Would like to create a progress indicator div using CSS animations? Check out the JSBin link provided. The desired behavior is to have the div width increase from 30% to 100% when the user clicks on stage3 after stage1, rather than starting from 0%. Althou ...

Changing color of entire SVG image: a step-by-step guide

Check out this SVG image I found: https://jsfiddle.net/hey0qvgk/3/ <?xml version="1.0" encoding="utf-8"?> <!-- Generator: Adobe Illustrator 19.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <svg version="1.1" width="90" height="9 ...

What is the best way to sort through an array depending on a specific sequence of elements provided

I am trying to create a custom pipe in Angular 5 that filters an array of events based on a given sequence. For instance, if my data is: ["submit", "click", "go_back", "click",...] I want to filter this data based on up to three inputs. If input ...

AngularJS RESTful Routing Masterclass

I am in the process of organizing my application using the Restful/Ruby convention /<resource>/[method]/[id]. In the past, when working with a server-side MVC framework like CodeIgniter, I would dynamically route based on the URI: For example: www. ...

Mastering the Art of Defining JavaScript Classes in React-Native

In my React Native project, I am faced with a situation where I need to create a new class: class customClass { email: string; name: string; constructor() { setUser(fbid: string, token: string): boolean { To keep things organized, I decide ...