Wild error after importing material UI in React app - javascript

I am trying to style my project with material UI and i am getting this unfamiliar error.
I've tried restarting my project multiple times. To no avail.
This is the error from my console:
ERROR in ../../../../../node_modules/#babel/runtime/helpers/esm/toConsumableArray.js 4:0-52
Module not found: Error: Can't resolve './nonIterableSpread' in '/Users/HP/node_modules/#babel/runtime/helpers/esm'
Did you mean 'nonIterableSpread.js'?
...
Navbar.js
import React from "react";
import { makeStyles } from "#material-ui/core/styles";
const useStyles = makeStyles((theme) => ({
root: {
display: "flex",
},
}));
function Navbar() {
const classes = useStyles();
return (
<>
<header className={classes.root}>
<div className="title">
<h1>Mba Okocha</h1>
</div>
</header>
</>
);
}
export default Navbar;

Related

How to fix "TypeError: Cannot read properties of undefined (reading 'useSystemColorMode')"

So I am using ChakraUI and React JS to make a project. Whenever I start the project it gives me the error, "TypeError: Cannot read properties of undefined (reading 'useSystemColorMode')".
I didn't edit any global theme or anything in chakra. I just started making the navbar, designed with CSS. And when I try to run it, it shows me the error.
here is my navbar component
import React from "react";
import { MenuItems } from "./MenuItems";
import "./navbar.css";
function Navbar() {
return (
<>
<nav className='NavbarItems'>
<h1 className='navbar-logo'></h1>
<div className='menu-icon'></div>
<ul>
{MenuItems.map((item, index) => {
return (
<li key={index}>
<a className={item.cname} href={item.url}>
{item.title}
</a>
</li>
);
})}
</ul>
</nav>
</>
);
}
export default Navbar;
Navbar CSS file
.NavbarItems {
height: 80px;
display: flex;
justify-content: center;
}
App.js file
import { ChakraProvider } from "#chakra-ui/provider";
import Navbar from "./components/navbar";
function App() {
return (
<ChakraProvider>
<Navbar />
</ChakraProvider>
);
}
export default App;
So basically this is a problem with ChakraUI theme,even though I did not do anything with ChakraUI theme or whatsoever.
I added theme.js file which included the following:
// theme.js
// 1. import `extendTheme` function
import { extendTheme } from "#chakra-ui/react";
// 2. Add your color mode config
const config = {
initialColorMode: "light",
useSystemColorMode: true,
};
// 3. extend the theme
const theme = extendTheme({ config });
export default theme;
then I included the following in index.js file:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { ColorModeScript } from "#chakra-ui/color-mode";
import theme from "./theme";
ReactDOM.render(
<React.StrictMode>
<ColorModeScript initialColorMode={theme.config.initialColorMode} />
<App />
</React.StrictMode>,
document.getElementById("root")
);
And it worked. If anyone facing the same problem, you can check out https://chakra-ui.com/docs/features/color-mode.
Once I used extendTheme instead of an object for theme the error was gone. https://chakra-ui.com/docs/theming/customize-theme
The first thing you should do is to check the name of the message type (error, success, warning)
if you misspell it, the error will occure

Can't get custom theme of Material UI to work

I'm trying to create a custom theme for my app using Material UI. Looking on how to do it, I found out I had to use the createTheme and the ThemeProvider. However for some reason, my theme is not overriding the default theme. In the following code you'll be able to see that I try to override the primary color with a brownish color, yeth the default blue still persists.
import {Button} from "#material-ui/core";
import {createTheme, ThemeProvider} from "#material-ui/core"
import {makeStyles} from "#material-ui/core";
const theme = createTheme({
pallete: {
primary: {
main: '#923223'
}
}
})
const App = () => {
return (
<ThemeProvider theme={theme}>
<div style={{backgroundColor: '#f8f8f8', height: '100%'}}>
<Button variant="contained" color="primary">algo</Button>
</div>
</ThemeProvider>
);
}
export default App;
Render:
Any clue to what's going on?

React - Error: Invalid hook call. Hooks can only be called inside of the body of a function component

I wanted to use "React Bootstrap Hamburger Menu" HamburgerMenu copied the code from there and I get an error errorScreen
"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:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem. "Here is my code
Mobile_Navbar.jsx
import React, { Component } from 'react';
import {
MDBNavbar,
MDBNavbarBrand,
MDBNavbarNav,
MDBNavItem,
MDBNavLink,
MDBNavbarToggler,
MDBCollapse,
MDBContainer
} from 'mdbreact';
import { BrowserRouter as Router } from 'react-router-dom';
class Test extends Component {
state = {
collapseID: ''
};
toggleCollapse = collapseID => () => {
this.setState(prevState => ({
collapseID: prevState.collapseID !== collapseID ? collapseID : ''
}));
};
render() {
return (
<Router>
<MDBContainer>
<MDBNavbar
color='light-blue lighten-4'
style={{ marginTop: '20px' }}
light
>
<MDBContainer>
<MDBNavbarBrand>Navbar</MDBNavbarBrand>
<MDBNavbarToggler
onClick={this.toggleCollapse('navbarCollapse1')}
/>
<MDBCollapse
id='navbarCollapse1'
isOpen={this.state.collapseID}
navbar
>
<MDBNavbarNav left>
<MDBNavItem active>
<MDBNavLink to='#!'>Home</MDBNavLink>
</MDBNavItem>
<MDBNavItem>
<MDBNavLink to='#!'>Link</MDBNavLink>
</MDBNavItem>
<MDBNavItem>
<MDBNavLink to='#!'>Profile</MDBNavLink>
</MDBNavItem>
</MDBNavbarNav>
</MDBCollapse>
</MDBContainer>
</MDBNavbar>
</MDBContainer>
</Router>
);
}
}
export default Test;
App.js
import React from 'react';
import './App.css';
import Test from './components/Mobile_Menu/Mobile_Navbar';
function App(props) {
return (
<div className="App">
<Test />
</div>
);
}
export default App;
It seems there is some kind of problem when we use the mdbootstrap Library MDBNavLink component. I didn't go deep on that to be able to explain why, though.
I solved this problem by importing the Link component from react-router-dom and use it instead with the className='nav-link'.
import { Link } from "react-router-dom";
//Snippet
// [....]
<MDBNavItem>
<Link
className='nav-link'
exact
to='/'
onClick={closeCollapse('mainNavbarCollapse')}
>
Home
</Link>
</MDBNavItem>
// [...]

Getting element type is invalid error when trying to populate cards with JSON data

I know this error has been posted many times, but none of the fixes worked for me. And i have been stuck with it for a week now...
I am learning react in my spare time, and i want to make a webpage that takes a json object, iterates through it to populate cards, and returns the cards. This is made in a component that i import into the main page. Here is the error:
Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of Dashboard.
import React from 'react';
import { CardHeader, Card } from "#material-ui/core";
import render from "react-dom";
export default function CardComponent() {
let bedpressJSONObject = {
bedpress: {
"0": {
bedriftsnavn: "hei",
dato: "24.12.12",
info: "asdasdsadas"
},
"1": {
bedriftsnavn: "på",
dato: "14.05.22",
info: "gfdsgdfsbvfbvsrgf"
},
"2": {
bedriftsnavn: "dei",
dato: "15.2.12",
info: "243wresdfvxzgbtr"
}
}
};
let cardList = [];
Object.keys(bedpressJSONObject.bedpress).forEach(index => {
let card = bedpressJSONObject.bedpress[index];
console.log(card.dato)
cardList.push(
<Card>
<CardHeader
title={card.bedriftsnavn}
subtitle={card.dato}
actAsExpander={true}
showExpandableButton={true}
/>
<p>{card.info}</p>
</Card>
);
});
{
return (
<div className="card-list">
{cardList}
</div>
);
}
}
And here is the main page:
import AppBar from "#material-ui/core/AppBar";
import { makeStyles } from "#material-ui/core/styles";
import Toolbar from "#material-ui/core/Toolbar";
import Typography from "#material-ui/core/Typography";
import "bootstrap/dist/css/bootstrap.min.css";
import React from "react";
import {CardComponent} from "../Components/CardsComponent";
import {DropdownMenu} from "../Components/DropdownComponent";
const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1
},
menuButton: {
marginRight: theme.spacing(2)
}
}));
export default function Dashboard() {
const classes = useStyles();
return (
<div className={classes.root}>
<div>
<AppBar position="static" style={{ backgroundColor: "#182b36" }}>
<Toolbar variant="dense">
<DropdownMenu />
<Typography variant="h6" color="inherit">
Dashboard
</Typography>
</Toolbar>
</AppBar>
</div>
<CardComponent/>
</div>
);
}
Any help or tips would be greatly appreciated!
Instead of import {CardComponent} from "../Components/CardsComponent";
Use import CardComponent from "../Components/CardsComponent";
You are using export default and not named exports in CardComponent.js
https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export

Class name hydration mismatch in server and client, (Warning: Prop `className` did not match Server and Client)

I don't know my issue is a bug or just a support term or just a configuration mismach, but I spend much time, Not happy go lucky writing here to somebody settle my issue. no!
I searched for 3 days, Even just sleep about 10 hours in this 3 days, try many ways, even I use Gitter but no one answer me, I see issues #10982 and #11506 and many Stack Overflow question and answers but I couldn't fix my issue and didn't find right way.
Absolutely I read and read many times the Material-UI Docs but I exactly did what the Docs said.
At last, I see class name hydration mismatch in server and client, 😞 this warning:
Warning: Prop `className` did not match. Server: "MuiFormLabel-root-134 MuiInputLabel-root-129 MuiInputLabel-formControl-130 MuiInputLabel-animated-133" Client: "MuiFormLabel-root-10 MuiInputLabel-root-5 MuiInputLabel-formControl-6 MuiInputLabel-animated-9"
I swear I tried many ways and searched a lot. I'm using Material-UI version 1.2.1.
This is my Index component as a root component:
import React, {Component} from 'react';
import Helmet from 'react-helmet';
import styles from 'StylesRoot/styles.pcss';
import TextField from '#material-ui/core/TextField';
export default class App extends Component {
render() {
return (
<div className={styles['root-wrapper']}>
<Helmet
htmlAttributes={{lang: 'fa', amp: undefined}}
bodyAttributes={{dir: 'rtl'}}
titleTemplate='اسکن - %s'
titleAttributes={{itemprop: 'name', lang: 'fa'}}
meta={[
{name: 'description', content: 'صفحه اتصال اعضاء'},
{name: 'viewport', content: 'width=device-width, initial-scale=1'},
]}
link={[{rel: 'stylesheet', href: '/dist/styles.css'}]}
/>
<TextField label='test' helperText='help'/>
</div>
);
};
}
Here below you can see my server.jsx and client.jsx:
//--------------------------------------------client.jsx
import React from 'react';
import {hydrate} from 'react-dom';
import {BrowserRouter} from 'react-router-dom';
import {MuiThemeProvider, createMuiTheme} from '#material-ui/core/styles';
import {lightBlue, red} from '#material-ui/core/colors';
import Index from './app/index';
import RTL from './app/public/rtl';
const theme = createMuiTheme({
palette: {
primary: lightBlue,
accent: red,
type: 'light',
},
direction: 'rtl',
});
class Main extends React.Component {
// Remove the server-side injected CSS.
componentDidMount() {
const jssStyles = document.getElementById('jss-server-side');
if (jssStyles && jssStyles.parentNode) {
jssStyles.parentNode.removeChild(jssStyles);
}
}
render() {
return (
<BrowserRouter>
<Index {...this.props}/>
</BrowserRouter>
);
}
}
hydrate((
<RTL>
<MuiThemeProvider theme={theme}>
<Main/>
</MuiThemeProvider>
</RTL>
), document.getElementById('root'));
//--------------------------------------------server.jsx
import React from 'react';
import {renderToString} from 'react-dom/server';
import {SheetsRegistry} from 'react-jss/lib/jss';
import JssProvider from 'react-jss/lib/JssProvider';
import {StaticRouter} from 'react-router-dom';
import {Helmet} from "react-helmet";
import {MuiThemeProvider, createMuiTheme, createGenerateClassName} from '#material-ui/core/styles';
import {red, lightBlue} from '#material-ui/core/colors';
import Template from './app/template';
import Index from './app/index';
import RTL from './app/public/rtl';
export default function serverRenderer({clientStats, serverStats}) {
return (req, res, next) => {
const context = {};
const sheetsRegistry = new SheetsRegistry();
const theme = createMuiTheme({
palette: {
primary: lightBlue,
accent: red,
type: 'light',
},
direction: 'rtl',
});
const generateClassName = createGenerateClassName();
const markup = renderToString(
<JssProvider registry={sheetsRegistry} generateClassName={generateClassName}>
<RTL>
<MuiThemeProvider theme={theme} sheetsManager={new Map()}>
<StaticRouter location={req.url} context={context}>
<Index/>
</StaticRouter>
</MuiThemeProvider>
</RTL>
</JssProvider>
);
const helmet = Helmet.renderStatic();
const jss = sheetsRegistry.toString();
res.status(200).send(Template({
markup: markup,
helmet: helmet,
jss: jss,
}));
};
}
So now it's needed to template.jsx:
export default ({ markup, helmet, jss }) => {
return `<!DOCTYPE html>
<html ${helmet.htmlAttributes.toString()}>
<head>
${helmet.title.toString()}
${helmet.meta.toString()}
${helmet.link.toString()}
<style id='jss-server-side'>${jss}</style>
</head>
<body ${helmet.bodyAttributes.toString()}>
<div id='root'>${markup}</div>
<script src='/dist/client.js' async></script>
</body>
</html>`;
};
Ok, Now it is possible that this question is asked What is RTL? and Why you wrap MuiThemeProvider inside it in both server and client?
So first see RTL component:
import React from 'react';
import {create} from 'jss';
import rtl from 'jss-rtl';
import JssProvider from 'react-jss/lib/JssProvider';
import {createGenerateClassName, jssPreset} from '#material-ui/core/styles';
const jss = create({plugins: [...jssPreset().plugins, rtl()]});
const generateClassName = createGenerateClassName();
export default props => (
<JssProvider jss={jss} generateClassName={generateClassName}>
{props.children}
</JssProvider>
);
I saw it in Material-UI Docs and I believe the documentation is a little poor and could be improved. I asked myself, Why documentation pass a props.children for this function? and I guess maybe this function should wrap something. so I try many shapes and it works. but in the first call in browser after build. when I refresh the browser then the warning appears 😞 and I see this damn shape:
Surely I wanna see below shape, but I see it just once after build:
I don't know what is going wrong. I leave an issue on Github too. And upload a mini repo for this issue, for seeing my issue just pull, and run npm install then num run dev. the project is accessible on localhost:4000
I don't know this way is proper or not, But it works well, Actually, I find out, using separate RTL Component, is not a good way, This cause to the inconsistency between server and client, I use the Right-to-Left Documentation page for each server and client-side separately, Hence omit the Rtl.jsx file and it's component from my project, So, server.jsx and client.jsx is like below:
//---------------------------------------------client.jsx
import React, {Component} from 'react';
import {hydrate} from 'react-dom';
import {BrowserRouter} from 'react-router-dom';
import {
MuiThemeProvider, createMuiTheme,
createGenerateClassName, jssPreset
} from '#material-ui/core/styles';
import {create} from 'jss';
import rtl from 'jss-rtl';
import JssProvider from 'react-jss/lib/JssProvider';
import {lightBlue, red} from '#material-ui/core/colors';
import Index from './app/index';
const theme = createMuiTheme({
palette: {
primary: lightBlue,
accent: red,
type: 'light',
},
direction: 'rtl',
});
const jssRTL = create({plugins: [...jssPreset().plugins, rtl()]});
const generateClassName = createGenerateClassName();
class Main extends Component {
componentDidMount() {
const jssStyles = document.getElementById('jss-server-side');
if (jssStyles) {
jssStyles.remove();
}
}
render() {
return (
<BrowserRouter>
<Index {...this.props}/>
</BrowserRouter>
);
}
}
hydrate((
<JssProvider jss={jssRTL} generateClassName={generateClassName}>
<MuiThemeProvider theme={theme}>
<Main/>
</MuiThemeProvider>
</JssProvider>
), document.getElementById('root'));
//---------------------------------------------server.jsx
import React from 'react';
import {renderToString} from 'react-dom/server';
import {SheetsRegistry} from 'react-jss/lib/jss';
import JssProvider from 'react-jss/lib/JssProvider';
import {StaticRouter} from 'react-router-dom';
import {Helmet} from "react-helmet";
import {
MuiThemeProvider, createMuiTheme,
createGenerateClassName, jssPreset
} from '#material-ui/core/styles';
import {create} from 'jss';
import rtl from 'jss-rtl';
import {red, lightBlue} from '#material-ui/core/colors';
import Template from './app/template';
import Index from './app/index';
export default function serverRenderer({clientStats, serverStats}) {
return (req, res, next) => {
const context = {};
const sheetsRegistry = new SheetsRegistry();
const theme = createMuiTheme({
palette: {
primary: lightBlue,
accent: red,
type: 'light',
},
direction: 'rtl',
});
const jssRTL = create({plugins: [...jssPreset().plugins, rtl()]});
const generateClassName = createGenerateClassName();
const markup = renderToString(
<JssProvider jss={jssRTL}
registry={sheetsRegistry}
generateClassName={generateClassName}>
<MuiThemeProvider theme={theme} sheetsManager={new Map()}>
<StaticRouter location={req.url} context={context}>
<Index pathname={req.url}/>
</StaticRouter>
</MuiThemeProvider>
</JssProvider>
);
const helmet = Helmet.renderStatic();
const jss = sheetsRegistry.toString();
res.status(200).send(Template({
markup,
helmet,
jss,
}));
};
}
It works well on both sides, server, and client and makes consistent Material-UI CSS in style tag.

Categories