React.useContext() keeps returning undefined? - javascript

I'm using Next.js and React, using react hooks + context to manage state. However, I've run into this issue, where React.useContext() returns undefined even though I'm passing in my context object (or so I think, anyway). Am I missing something really obvious? What's happening?
I've created the context in a const called CartContext, and then in my provider component, I have created the value object and passed it as a prop to CartContext.Provider (see below, in _app.js). I made sure the context provider was wrapping my components by adding an <h1> element just to make sure.
The problem seems to occur in index.js. I've imported the CartContext from ./_app.js and then passed it as the argument to useContext() which is supposedly what I should do, but it keeps throwing this error:
"TypeError: Cannot destructure property 'firstSample' of 'react__WEBPACK_IMPORTED_MODULE_0___default.a.useContext(...)' as it is undefined"
which from what I have gathered tells me that useContext() is returning undefined.
_app.js (wraps all pages)
import React from 'react'
import '../styles/global.css';
import theme from '../components/customTheme';
import { ThemeProvider } from '#material-ui/core/styles';
const MyApp = props => {
const { Component, pageProps, store } = props
return (
<ContextProvider>
<ThemeProvider theme={theme}>
<Component {...pageProps} />
</ThemeProvider>
</ContextProvider>
)
}
// Context
export const CartContext = React.createContext()
function ContextProvider({ children }) {
const value = {
firstSample: "Test",
exampleFunction: () => {alert("Hello World")},
}
return (
<CartContext.Provider value={value}>
<h1>The provider works</h1>
{children}
</CartContext.Provider>
)
}
export default MyApp;
index.js
import Nav from '../components/nav';
import Footer from '../components/footer';
import Product from '../components/product';
import { makeStyles } from '#material-ui/core/styles';
import CartContext from './_app';
import {
Typography,
Button
} from '#material-ui/core';
const useStyles = makeStyles({
body: {
margin: '13vh 0 3vh',
backgroundColor: ' white',
textAlign: 'left'
},
earnWrapper: {
display: 'block',
textAlign: 'left',
backgroundColor: 'white',
width: 'calc(100% - 4vh)',
margin: '5% 2vh 12%',
borderRadius: '25px',
transition: '0.3s',
boxShadow: '0px 5px 20px #dedede'
},
earnContent: {
padding: '7%',
textAlign: 'left',
display: 'inline-block'
},
earntCaption: {
color: 'grey',
},
earntAmount: {
margin: '0.5vh 0 1.5vh'
},
withdraw: {
width: '130px',
height: '40px'
},
shareInfo: {
margin: '5% 2vh',
textAlign: 'left'
},
products: {
textAlign: 'center ',
width: '100%'
}
});
export default function Home(props) {
const styles = useStyles();
// Grab data from parent context
const { firstSample } = React.useContext(
CartContext
)
return (
<div>
<DefaultHead
title="Oorigin | Home"
/>
<Nav isLoggedIn={true} />
<div className={styles.body}>
<div className={styles.earnWrapper}>
<div className={styles.earnContent}>
<Typography className={styles.earntCaption} variant="caption">You've earned</Typography>
<Typography className={styles.earntAmount} variant="h4">S$18.50</Typography>
<Button className={styles.withdraw} disableElevation variant="contained" color="primary">Withdraw</Button>
</div>
</div>
<div className={styles.shareInfo}>
<Typography><b>Shop, Share, Earn</b></Typography>
<Typography><br/>Shop products you like, share products you love, and earn up to 10% commission on every qualifying sale you refer</Typography>
</div>
<div className={styles.products}>
<Product
imgURL="../TestItem1.svg"
imgAlt="Test Product"
title="Disinfecting Air Purifying Solution"
price={(22.80).toFixed(2)}
link="/products/staticProduct"
/>
<Product
imgURL="../TestItem2.svg"
imgAlt="Test Product"
title="Disinfecting Air Purifying Solution"
price={(22.80).toFixed(2)}
/>
<Product
imgURL="../TestItem3.svg"
imgAlt="Test Product"
title="Disinfecting Air Purifying Solution"
price={(22.80).toFixed(2)}
/>
<Product
imgURL="../TestItem4.svg"
imgAlt="Test Product"
title="Disinfecting Air Purifying Solution"
price={(22.80).toFixed(2)}
/>
</div>
</div>
<Footer/>
<h1>{firstSample}</h1>
</div>
);
}

Ok so it was a really simple mistake, I imported CartContext in index.js as
import cartContex from _app.js, when it should be with curley brackets because it is not the default export. So the corrected (functional) code is simply: import { cartContext } from _app.js

There are some problems with your code, I do not understand why your createContext stays with the component<MyApp />.
Problems:
In the MyApp component you are doingexport default MyApp and export CartContext, I believe this is not possible.
Your createContext is without adefaultValue, maybe that's the reason to return undefined. See the example in the documentation
I believe that by making these changes your code should work, or at least you can evolve with your problem.
It would be easier to help with a codesandbox.

Try to import like this :
import { CartContext } from './_app';

Related

using theme.spacing inside theme definition

I have the following theme setup:
export const themeDefault = createTheme({
themeName: 'Default (Mortgage Hub)',
spacing: 4,
...typography,
palette,
components: {
MuiButton: {
styleOverrides: {
root: {
paddingLeft: theme.spacing(12),
paddingRight: theme.spacing(4),
border: '10px',
},
},
},
},
})
And I would like to use theme.spacing inside however, of course. Theme is not defined yet. I have tried to use makeStyles & useTheme however these are hooks. So of course they will not work.
Are you able to supply styleOverrides once the theme has been indicated?
The styleOverrides feature of the theme is extremely powerful and versatile. In the Overrides based on props portion of the documentation, you can find an example of specifying a callback within the styleOverrides which then gives you access to the component's props and state (via ownerState) and the theme.
Below is an example showing how the callback syntax gives you access to the theme as well as showing how you can leverage ownerState to do conditional styles based on the props passed to a component (e.g. based on whether or not startIcon was specified or which variant was used or any combination of interest).
import * as React from "react";
import Stack from "#mui/material/Stack";
import Button from "#mui/material/Button";
import { createTheme, ThemeProvider } from "#mui/material/styles";
import SaveIcon from "#mui/icons-material/Save";
const theme = createTheme({
themeName: "Default (Mortgage Hub)",
spacing: 4,
components: {
MuiButton: {
styleOverrides: {
root: ({ ownerState, theme }) => {
const conditionalStyles = {};
if (ownerState.startIcon !== undefined) {
conditionalStyles.paddingLeft = theme.spacing(6);
if (ownerState.variant === "outlined") {
conditionalStyles.border = "5px solid black";
conditionalStyles["&:hover"] = { border: "5px solid grey" };
}
} else {
conditionalStyles.paddingLeft = theme.spacing(4);
}
return {
...conditionalStyles,
paddingRight: theme.spacing(4)
};
}
}
}
}
});
export default function BasicButtons() {
return (
<ThemeProvider theme={theme}>
<Stack spacing={2} direction="row">
<Button variant="text">Text</Button>
<Button variant="contained">Contained</Button>
<Button variant="outlined">Outlined</Button>
<Button startIcon={<SaveIcon />} variant="contained">
Contained with startIcon
</Button>
<Button startIcon={<SaveIcon />} variant="outlined">
Outlined with startIcon
</Button>
</Stack>
</ThemeProvider>
);
}

Problems with React Router/Hoook

Update (new changes):
So now I pretty much converted my code to a functional component however it is as if nothing is being returned from the API, or perhaps I am not "mounting" correctly? I get the error " TypeError: Cannot read property 'map' of undefined" meaning nothing is being returned but I'm not sure why. Help?
Old post (I had previously tried to use a hook in a a class component):
I'm pretty brand new to react and recently I have been getting this error from when trying to navigate to a page on click of a card media (using material ui). So I pretty much follow the instruction to push to history the route to the page I want to navigate to via a function and call that function when I click the media card. Below is my code and the error I get. Do you have any idea why I might be having an issue with this?
My updated code
import Card from '#material-ui/core/Card';
import CardMedia from '#material-ui/core/CardMedia';
import Grid from '#material-ui/core/Grid';
import Container from '#material-ui/core/Container';
import {getItems} from "../Network/network_utility";
import {useHistory} from "react-router-dom";
import {makeStyles} from '#material-ui/core/styles';
import React, {useState, useEffect} from "react";
const useStyles = makeStyles(theme => ({
icon: {
marginRight: theme.spacing(2),
},
heroContent: {
padding: theme.spacing(8, 0, 6),
},
cardGrid: {
paddingTop: theme.spacing(6),
paddingBottom: theme.spacing(3),
position: "fixed"
}
}));
export default function Items() {
let history = useHistory();
const classes = useStyles();
const useFeaturedItems = () => {
const [featured_items, setFeaturedItems] = useState([]);
useEffect(() => {
getItems(1).then(response => setFeaturedItems(response["data"]))}, []);
return featured_items;
};
return (
<div>
<Container className={classes.cardGrid} maxWidth="lg">
<Grid container spacing={6}>
{useFeaturedItems().map((card, index) => (
<Grid item key={index} xs={16} sm={4} md={2}>
<Card raised={false} style={{height: "30vh", width: "20vh"}}>
<CardMedia
component="img"
src={card["thumbnail"]}
style={{height: "25vh", width: "20vh"}}
onClick={history.push("/item")}
>
</CardMedia>
<div style={{paddingLeft: "10px", paddingTop: "10px"}}>
<text style={{
whiteSpace: "nowrap",
overflow: "hidden",
display: "block",
textOverflow: "ellipsis"
}}>
{card["title"]}
</text>
</div>
</Card>
</Grid>
))}
</Grid>
</Container>
</div>
);
}
As I can see you are using hook inside a class component. It is not possibile
how use hook
You can’t use Hooks inside a class component, but you can definitely mix classes and function components with Hooks in a single tree. Whether a component is a class or a function that uses Hooks is an implementation detail of that component. In the longer term, we expect Hooks to be the primary way people write React components.
In class component you need to use the HOC withRouter. After that you can access the history through props with this.props.history

backgroundImage is not working react, just the default white background

So I am making a react app, and I think it's better to show you the code than explain:
Body.js:
import React from 'react';
import Clearsky from "Images/clearsky.jpg";
import Rain from "Images/clearsky.jpg";
import Cloudy from "Images/clearsky.jpg";
const type = {
CLEARSKY: "clearsky",
RAIN: "rain",
CLOUDY: "cloudy"
}
class LeftSide extends React.Component {
constructor(props) {
super(props);
this.state = {
type: this.props.type,
degrees: this.props.degrees
}
}
render() {
return (
""
);
}
}
export default function Body() {
//This is printing the correct path and if I type it in the browser I can see the image.
console.log(type.CLEARSKY);
const style = {
//Not working
backgroundImage: `url(${Clearsky})`
}
return (
<div className="body" style={style}>
<LeftSide />
</div>
);
}
Header.js (uses material-ui.com):
import React from 'react';
import { makeStyles } from '#material-ui/core/styles';
import AppBar from '#material-ui/core/AppBar';
import Toolbar from '#material-ui/core/Toolbar';
import Typography from '#material-ui/core/Typography';
import IconButton from '#material-ui/core/IconButton';
import MenuIcon from '#material-ui/icons/Menu';
import logo from "Images/icon.png";
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
menuButton: {
marginRight: theme.spacing(2),
},
title: {
flexGrow: 1,
},
}));
export default function Header() {
const classes = useStyles();
return (
<div className={classes.root}>
<AppBar position="fixed" style={{ borderRadius: "25px"}}>
<Toolbar>
<IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="menu">
<MenuIcon />
</IconButton>
<Typography variant="h6" className={classes.title}>
Weather
</Typography>
<img src={logo} alt="Icon" height="50" width="50" />
</Toolbar>
</AppBar>
</div>
);
}
index.js:
import React from "react";
import ReactDOM from "react-dom";
import Header from "./Header.js";
import Body from "./Body.js";
export default function App() {
return (
<div className="App">
<Header />
<Body />
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
However the backgroundImage on Body.js is not working, just the default white background.
Tried:
Image from an online server (not a local image).
Setting backgroundSize.
EDIT:
My directory:
src:
Images:
EDIT 2:
I have noticed that if I change the LeftSide component to return
<p>A</p>
Instead of "" it will render this in the browser:
Part of the image has been rendered.
Now I believe it is something with the css.
Solved by adding the following css:
const style = {
//Now working
backgroundImage: `url(${Clearsky})`,
height: "100vh",
backgroundSize: "cover",
}
The issue was the height and the size.
I believe your code is correct, but the div with the background has no width and height enough to be visible. Please check if this is the case.
Working sample (see lines 31 and 32): https://codesandbox.io/s/holy-pine-wpdw7

Bold active menu after refreshing the page

I have an application has been written with React + Redux and Antdesign. My application is a dashboard app. So I used the layout in Ant design https://ant.design/components/layout/
When I click on side menus, the active menu gets bold which is fine. But I need when I refresh the page, it checks and detect the route and bold related menu item.
I have a Sidebar component which is stateful. Inside it, in componentDidMount I call a function which will dispatch an action from mapDispatchToProps. The reducer changes the state. But in HTML codes, in defaultSelectedKeys, I can not set the number of active menus.
Sidebar.js component:
import React from 'react';
import { render } from 'react-dom';
import { connect } from 'react-redux'
import { Switch, BrowserRouter, Route, Link } from 'react-router-dom';
// antd
import { Layout, Breadcrumb, Menu, Icon } from 'antd';
const { Header, Content, Footer, Sider } = Layout;
// Helpers
import { Alert } from '../helpers/notifications';
// Components
import Home from '../components/Home';
// import Header from '../components/Header';
import NotFound from '../components/NotFound';
import PostsEditor from '../components/Posts/PostsEditor';
// Actions
import { setRouteActiveFlag } from '../actions/ui.action'
class Sidebar extends React.Component {
componentDidMount () {
const routes = {
'/' : 1,
'/posts' : 2,
'/logout' : 3
}
this.props.detectActiveRoute(setRouteActiveFlag({
routes:routes,
path:window.location.pathname
}))
}
render() {
const { selectedRoute } = this.props;
console.log(selectedRoute);
return (
<div>
<Layout>
<Sider
style={{
overflow: 'auto',
height: '100vh',
position: 'fixed',
left: 0,
}}
breakpoint="lg"
collapsedWidth="0"
onBreakpoint={broken => {
console.log(broken);
}}
onCollapse={(collapsed, type) => {
console.log(collapsed, type);
}}
>
<div className="logo" >
Logo <br/><br/><br/>
</div>
<Menu theme="dark" mode="inline" style={{ lineHeight: '64px' }} defaultSelectedKeys={[selectedRoute.toString() || '1']}>
<Menu.Item key="1">
<Link to="/" style={{ color:'#fff' }}>
<Icon type="user" />
<span className="nav-text">Home</span>
</Link>
</Menu.Item>
<Menu.Item key="2">
<Link to="/posts" style={{ color:'#fff' }}>
<Icon type="user" />
<span className="nav-text">Posts</span>
</Link>
</Menu.Item>
<Menu.Item key="3">
<a href="/logout" style={{ color:'#fff' }}>
<Icon type="user" />
<span className="nav-text">Logout</span>
</a>
</Menu.Item>
</Menu>
</Sider>
<Layout style={{ marginLeft: 200 }}>
<Content style={{ margin: '24px 16px 0', overflow: 'initial'}}>
<Breadcrumb style={{ margin: '0 0 20px 0' }}>
<Breadcrumb.Item>Home</Breadcrumb.Item>
<Breadcrumb.Item>List</Breadcrumb.Item>
<Breadcrumb.Item>App</Breadcrumb.Item>
</Breadcrumb>
<div style={{ padding: 24, background: '#fff', minHeight: 360 }}>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/posts/:id?" component={PostsEditor} />
<Route component={NotFound}/>
</Switch>
<Alert stack={ { limit: 3 } } />
</div>
</Content>
<Footer style={{ textAlign: 'center' }}>Ant Design ©2018 Created by Ant UED</Footer>
</Layout>
</Layout>
</div>
);
}
}
const mapStateToProps = (state, ownProps) => {
return {
state: state,
props: ownProps,
selectedRoute:state.ui.selectedRoute || 1
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
detectActiveRoute: (obj) => dispatch(obj)
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Sidebar)
ui.action.js
export const setRouteActiveFlag = (payload = 'global') => ({
type: actions.SET_ROUTE_ACTIVE_FLAG,
payload
});
ui.reducer.js
import { handleActions } from 'redux-actions';
import Immutable from 'seamless-immutable';
import * as actions from '../consts/action-types';
const initialState = Immutable({
requests: {},
selectedRoute:{}
});
export default handleActions({
[actions.SET_ROUTE_ACTIVE_FLAG]: (state, action) => {
if (action.payload.routes && action.payload.path && action.payload.routes[ action.payload.path ]) {
return state.set('selectedRoute', action.payload.routes[ action.payload.path ])
}else{
return state.set('selectedRoute', 1)
}
}
}, initialState);
Please help me find the best and simple practices.
There is no need to use redux, just use react-router to get current pathname and pass it to defaultSelectedKeys.
<Menu defaultSelectedKeys={[this.props.location.pathname]}>
...
.....
</Menu>
Look at this answer , if you don't know how to get pathname
The following answer assumes you are using hooks. I know that from your question you are not using hooks, but it could be useful for other people. This answer works not only when refreshing but also when pressing the back and forward buttons:
import React, { useState, useEffect } from 'react'
import { useHistory, useLocation } from 'react-router-dom'
import { Layout, Menu } from 'antd'
const { Sider } = Layout
const items = [
{ key: '1', label: 'Invoices', path: '/admin/invoices' },
{ key: '2', label: 'Service Details', path: '/admin/service-details' },
{ key: '3', label: 'Service Contract Details', path: '/admin/service-contract-details' },
{ key: '4', label: 'Cost Centers', path: '/admin/cost-centers' },
{ key: '5', label: 'Clients', path: '/admin/clients' },
{ key: '6', label: 'Vendors', path: '/admin/vendors' }
]
const Sidebar = () => {
const location = useLocation()
const history = useHistory()
const [selectedKey, setSelectedKey] = useState(items.find(_item => location.pathname.startsWith(_item.path)).key)
const onClickMenu = (item) => {
const clicked = items.find(_item => _item.key === item.key)
history.push(clicked.path)
}
useEffect(() => {
setSelectedKey(items.find(_item => location.pathname.startsWith(_item.path)).key)
}, [location])
return (
<Sider style={{ backgroundColor: 'white' }}>
<h3 style={{ paddingLeft: '1rem', paddingTop: '1rem', fontSize: '1.25rem', fontWeight: 'bold', minHeight: 64, margin: 0 }}>
Costek
</h3>
<Menu selectedKeys={[selectedKey]} mode='inline' onClick={onClickMenu}>
{items.map((item) => (
<Menu.Item key={item.key}>{item.label}</Menu.Item>
))}
</Menu>
</Sider>
)
}
export default Sidebar
Your sidebar will look as follows:
You can add any css in your menu by conditioning and adding a class just in this way.
<MenuItem className={ (this.props.location.pathname==='/yourRoute')? 'active' : '' } >
</MenuItem>
In case if you get any kind of undefined error then you can use the 'withRouter' HOC
in this way.
In your component where you want to get that location prop, you will first import
import {withRouter} from 'react-router-dom';
then you can export it in this way.
export default withRouter(YourComponent);
Final code can look somewhat similar to this
import React, {Fragment, Component} from 'react';
import {withRouter, Link } from 'react-router-dom';
class Menu extends Component {
render(){
const {pathname} = this.props.location;
return (
<Fragment>
<div id="sidebar-menu" className="sidebar-menu">
<ul>
<li className={(pathname==='/dashboard' || pathname==='/')?'active':''}>
<Link to="/dashboard">Dashboard</Link>
</li>
<li className={(pathname==='/properties')?'active':''}>
<Link to="/properties">Properties</Link>
</li>
</ul>
</div>
</Fragment>
);
}
}
export default withRouter(Menu);

Warning: Prop `className` did not match ~ Material UI css arbitrarily breaks on reload

Video reproducing the error/missing css
I know there are already dated versions of this question on stack overflow, like React + Material-UI - Warning: Prop className did not match.
However, when I attempt to google and research people's solutions, there is just no clear answer. Any answers I could find don't match my stack.
My stack:
Node JS
Next JS
Material UI
And from what I could glean from answers to questions like next.js & material-ui - getting them to work is that there is some measure of incompatibility when it comes to Next JS and Material UI.
Code-wise, here is my Appbar component. Initially I was not exporting my useStyles object, but I ended up doing it in a pitiful attempt to follow along with Material UI's express guide to "server rendering". There has to be a fix that doesn't involve changing like every file I have.
import React from 'react';
import AppBar from '#material-ui/core/AppBar';
import Toolbar from '#material-ui/core/Toolbar';
import IconButton from '#material-ui/core/IconButton';
import Typography from '#material-ui/core/Typography';
import InputBase from '#material-ui/core/InputBase';
import { fade } from '#material-ui/core/styles/colorManipulator';
import { makeStyles } from '#material-ui/core/styles';
import MenuIcon from '#material-ui/icons/Menu';
import SearchIcon from '#material-ui/icons/Search';
import {connectSearchBox} from 'react-instantsearch-dom';
const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1,
},
menuButton: {
marginRight: theme.spacing(2),
},
title: {
flexGrow: 1,
display: 'none',
[theme.breakpoints.up('sm')]: {
display: 'block',
},
},
search: {
position: 'relative',
borderRadius: theme.shape.borderRadius,
backgroundColor: fade(theme.palette.common.white, 0.15),
'&:hover': {
backgroundColor: fade(theme.palette.common.white, 0.25),
},
marginLeft: 0,
width: '100%',
[theme.breakpoints.up('sm')]: {
marginLeft: theme.spacing(1),
width: 'auto',
},
},
searchIcon: {
width: theme.spacing(7),
height: '100%',
position: 'absolute',
pointerEvents: 'none',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
inputRoot: {
color: 'inherit',
},
inputInput: {
padding: theme.spacing(1, 1, 1, 7),
transition: theme.transitions.create('width'),
width: '100%',
[theme.breakpoints.up('sm')]: {
width: 300,
'&:focus': {
width: 400,
},
},
}
}));
function SearchBox({currentRefinement, refine}){
const classes = useStyles();
return(
<InputBase
type="search"
value={currentRefinement}
onChange={event => refine(event.currentTarget.value)}
placeholder="Search by state, park name, keywords..."
classes = {{
root: classes.inputRoot,
input: classes.inputInput,
}}
/>
)
}
const CustomSearchBox = connectSearchBox(SearchBox);
function SearchAppBar() {
const classes = useStyles();
return (
<div className={classes.root}>
<AppBar position="static" color="primary">
<Toolbar>
<IconButton
edge="start"
className={classes.menuButton}
color="inherit"
aria-label="Open drawer"
>
<MenuIcon />
</IconButton>
<Typography className={classes.title} variant="h6" noWrap>
Title
</Typography>
<div className={classes.search}>
<div className={classes.searchIcon}>
<SearchIcon />
</div>
<CustomSearchBox/>
</div>
</Toolbar>
</AppBar>
</div>
);
}
export {SearchAppBar, useStyles};
I was just digging around random parts of the internet looking for answers to this error, accidentally npm install'ed styled-components as part of this answer on a Github issue (because they have a very similar object to the counterpart in Material UI called ServerStyleSheet (vs Material UI's ServerStyleSheets), so obviously that didn't work.
BUT......... I ended up just using the ServerStyleSheet fix to try to make it agreeable with Material UI's ServerStyleSheets object, and ended up with this new _document.js.
I'm still dumbfounded I was able to refactor an entirely different fix to make this work but I tested it and it fixes the problem entirely, now reloads are fine.
import Document, { Html, Head, Main, NextScript } from 'next/document';
import {ServerStyleSheets} from "#material-ui/styles";
class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheets();
const originalRenderPage = ctx.renderPage;
try{
ctx.renderPage = () => originalRenderPage({
enhanceApp: App => props => sheet.collect(<App {...props}/>)
});
const initialProps = await Document.getInitialProps(ctx);
return { ...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
)
}
} finally {
ctx.renderPage(sheet)
}
}
render() {
return (
<Html>
<Head>
<link rel="shortcut icon" type="image/png" href="../static/favicon.ico"/>
<style>{`body { margin: 0 } /* custom! */`}</style>
<meta name="viewport"content="width=device-width, initial-scale=1.0" />
</Head>
<body className="custom_class">
<Main />
<NextScript />
</body>
</Html>
)}
}
export default MyDocument;
If you wanna see how crazy it was that it worked, here is the fix for the same error in styled-components:
export default MyDocument;
import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'
export default class MyDocument extends Document {
static async getInitialProps (ctx) {
const sheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: App => props => sheet.collectStyles(<App {...props} />)
})
const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
)
}
} finally {
sheet.seal()
}
}
}
I hope this helped someone with the mess that is Material-UI + Next.js
For my part, adding { name: "MuiExample_Component" } in the makeStyle hook works for some reason. I found this solution while digging on internet. I would appreciate if someone could tell me if it's a good solution or not, but here is the code :
const useStyles = makeStyles({
card: {
backgroundColor: "#f7f7f7",
width: "33%",
},
title: {
color: "#0ab5db",
fontWeight: "bold",
},
description: {
fontSize: "1em"
}
}, { name: "MuiExample_Component" });

Categories