blank page on "npm run serve" after build - javascript

I am working with Material-ui. after building the project with npm run build, it shows blank page on running npm run serve
I have tried setting homepage: "./" in the package.json as from here, it's still showing blank page. is it from MUI or am I missing something in my code.
Checking the console in the browser I get this error.
index.js
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
import reportWebVitals from "./reportWebVitals";
import { MoralisProvider } from "react-moralis";
import { App } from "./App";
const appID =
process.env.REACT_APP_MORALIS_APP_ID;
const serverUrl =
process.env.REACT_APP_MORALIS_SERVER_URL;
ReactDOM.render(
<React.StrictMode>
<MoralisProvider appId={appID} serverUrl={serverUrl}>
<BrowserRouter>
<App />
</BrowserRouter>
</MoralisProvider>
</React.StrictMode>,
document.getElementById("root")
);
reportWebVitals();
app.js
import Auth from "./components/header";
import Pannel from "./components/bottomNav";
import Profile from "./components/profile";
import Betting from "./components/betting";
import Raffle from "./components/raffle";
// import useMediaQuery from "#mui/material/useMediaQuery";
import { CssBaseline } from "#mui/material";
import { ThemeProvider, createTheme } from "#mui/material/styles";
import React, { useMemo, useState } from "react";
import { Routes, Route } from "react-router-dom";
const ColorModeContext = React.createContext({ toggleColorMode: () => {} });
function App() {
// const prefersDarkMode = useMediaQuery("(prefers-color-scheme: dark)");
// prefersDarkMode ? "dark" : "light"
const [mode, setMode] = useState("dark");
const theme = useMemo(
() =>
createTheme({
palette: {
mode,
primary: {
main: "#ffff00",
dark: "#10294c",
},
secondary: {
main: "#ffb400",
},
},
}),
[mode]
);
const colorMode = useMemo(
() => ({
toggleColorMode: () => {
setMode((prevMode) => (prevMode === "light" ? "dark" : "light"));
},
}),
[]
);
return (
<ColorModeContext.Provider value={colorMode}>
<ThemeProvider theme={theme}>
<CssBaseline />
<Auth />
<Routes>
<Route path="/" element={<Profile />} />
<Route path="bet" element={<Betting />} />
<Route path="lottery" element={<Raffle />} />
</Routes>
<Pannel />
</ThemeProvider>
</ColorModeContext.Provider>
);
}
export { App, ColorModeContext };
however it renders properly on local development

i figured this out debugging from the break-point. it turns out that i made use of react useEffects and useEthers from usedapp/core somewhere in my project that raised the reactdom invalid variant error.
a library hook from useEthers was redundant as i did not initialise the web3 provider for my project

Related

React - Invalid Hook Call: convert App component to functional component, still get Invalid Hook Call

I have tried to create a simple app that allows a user to create or edit exiting 'projects'.
I am running in to the error:
react.development.js:1476 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
//
at Routes (http://localhost:3000/static/js/bundle.js:154234:5)
at App
//
The code for my 'App.js' is:
import React from "react";
import { Routes, Route } from "react-router-dom";
import MainPage from "./MainPage";
//import LoginPage from "./LoginPage";
//<Route path="/login" element={<LoginPage />} />;
const App = () => {
return (
<Routes>
<Route path="/projects" element={<MainPage />} />
</Routes>
);
};
export default App;
Nothing renders in the browser but the console throws the above error. I thought the error was related to using a functional component, but that doesn't seem to fix it (or more likely I'm too daft to figure out what I've done wrong).
I originally had the following code:
import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import MainPage from './MainPage';
import LoginPage from './LoginPage';
const App = () => (
<Router>
<Switch>
<Route path="/login" component={LoginPage} />
<Route path="/projects" component={MainPage} />
</Switch>
</Router>
);
export default App;
I realised 'switch' needed to be replaced with 'routes' and based on other online documentation used the 'elements' prop instaed of the component prop.
import React from 'react';
import { Routes, Route } from 'react-router-dom';
import MainPage from './MainPage';
import LoginPage from './LoginPage';
const App = () => {
return (
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route path="/projects" element={<MainPage />} />
</Routes>
);
};
export default App;`
Clearly this wan't the solution.
My MainPage.js code is:
import React, { useState, useEffect } from 'react';
import {
Button,
DataTable,
TableContainer,
Table,
TableHead,
TableRow,
TableBody,
TableCell,
} from 'carbon-components-react';
const MainPage = () => {
// State for the list of projects
const [projects, setProjects] = useState([]);
// Fetch the list of projects from the server when the component mounts
useEffect(() => {
fetch('/api/projects')
.then((res) => res.json())
.then((data) => setProjects(data.projects));
}, []);
// Function to handle creating a new project
const handleCreateProject = () => {
// Display a form for the user to enter the project's name
const projectName = window.prompt('Enter the name of the new project:');
// If the user entered a name, create the new project and add it to the list
if (projectName) {
fetch('/api/projects', {
method: 'POST',
body: JSON.stringify({ name: projectName }),
headers: { 'Content-Type': 'application/json' },
})
.then((res) => res.json())
.then((data) => setProjects([...projects, data.project]));
}
};
return (
<div>
<h1>My Projects</h1>
<Button onClick={handleCreateProject}>Create New Project</Button>
<TableContainer>
<Table>
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
</TableRow>
</TableHead>
<TableBody>
{projects.map((project) => (
<TableRow key={project.id}>
<TableCell>{project.name}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
</div>
);
};
export default MainPage;
The LoginPage was just a placeholder (removed in the updated App.js).
My index.js code is:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
My package.json dependencies are:
"dependencies": {
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
Update:
Updated App.js now using RouterProvider, createBrowserRouter. This is now throwing a browser console error:
Cannot read properties of undefined (reading 'map')
This seems to be coming from
return routes.map((route) => {
In the components.tsx file.
Current App.js code is:
import React from "react";
import { RouterProvider, createBrowserRouter } from "react-router-dom";
import { Routes, Route } from "react-router-dom";
import MainPage from "./MainPage";
//import LoginPage from "./LoginPage";
const router = createBrowserRouter();
const routes = [
{ path: "/projects", element: <MainPage /> },
//{ path: '/login', element: <LoginPage /> },
// add more routes here
];
const App = () => {
return (
<RouterProvider router={router}>
<Routes>
{routes.map((route) => (
<Route path={route.path} element={route.element} />
))}
</Routes>
</RouterProvider>
);
};
export default App;
The initial code:
import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import MainPage from './MainPage';
import LoginPage from './LoginPage';
const App = () => (
<Router>
<Switch>
<Route path="/login" component={LoginPage} />
<Route path="/projects" component={MainPage} />
</Switch>
</Router>
);
export default App;
When you updated from react-router-dom v5 to v6, i.e. replace the Switch component with the Routes component and changed the Route props, you appear to have dropped the Router component. A router is still required.
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import MainPage from './MainPage';
import LoginPage from './LoginPage';
const App = () => (
<Router>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route path="/projects" element={<MainPage />} />
</routes>
</Router>
);
export default App;
You shared your project's dependencies but I don't see react-router-dom listed as a project dependency. Ensure react-router-dom is actually installed and that the package.json file lists it as a dependency.
npm install --save react-router-dom#6
If you are trying to use the newer RRDv6.4+ Data APIs then you specify all the routes in the createBrowserRouter function. In your example it's not passed an array of routes, so this seems to be the cause of the mapping error. Pass the routes configuration array to createBrowserRouter. The RouterProvider also takes no children, it's self-closed.
import React from "react";
import { RouterProvider, createBrowserRouter } from "react-router-dom";
import { Routes, Route } from "react-router-dom";
import MainPage from "./MainPage";
import LoginPage from "./LoginPage";
// Routes configuration array
const routes = [
{ path: "/projects", element: <MainPage /> },
{ path: '/login', element: <LoginPage /> },
// add more routes here
];
// Pass configuration array
const router = createBrowserRouter(routes);
const App = () => {
return (
<RouterProvider router={router} />
);
};
If you are using latest react-router-dom v6.4+ then you need to add RouterProvider in your root file and create router configuration using createBrowserRouter .
Update your index.js
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { RouterProvider, createBrowserRouter } from "react-router-dom";
import MainPage from "./MainPage";
import LoginPage from "./LoginPage";
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
const router = createBrowserRouter([
{
path: "/",
element: <MainPage />
},
{
path: "/login",
element: <LoginPage />
}
]);
root.render(
<StrictMode>
<RouterProvider router={router} />
</StrictMode>
);

React hooks can also use the navLink, Link, Navigator, useNavigator of react-router v6.x to jump

No matter which api I use to navigate, it doesn't take effect, or it reports an error or a blank page. Below is the configuration of my index.js and router.
index.js:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
// import App from './App';
import reportWebVitals from './reportWebVitals';
import 'lib-flexible'
import Router from './router/index';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Router />
</React.StrictMode>
);
reportWebVitals();
router.js:
import React, { useEffect, lazy } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import "../global.scss";
import NavWrapper from "../components/navs"
const AIPage = lazy(() => import("../pages/AI"))
const BridgePage = lazy(() => import("../pages/Bridge"))
const PipelinePage = lazy(() => import("../pages/Pipeline"))
const BasicRoute = () => {
useEffect(() => {
// console.log(window.location.pathname)
const AIThemes = {
'--app-themeColor': 'linear-gradient(270deg, #64e6c0 0%, #687ff9 100%)',
'--app-border-color': '1px solid #6880F98C',
'--app-background': '#262335'
}
const PipeThemes = {
'--app-themeColor': 'linear-gradient(270deg, #1B74D4 0%, #25BC90 100%)',
'--app-border-color': '1px solid #25BC90',
'--app-background': '#262335'
}
const declaration = document.getElementsByTagName('body')[0].style
if (window.location.pathname === "/pipeline") {
for (let key in PipeThemes) {
declaration.setProperty(key, PipeThemes[key])
}
} else if (window.location.pathname === "/" || window.location.pathname === "/ai") {
for (let key in AIThemes) {
declaration.setProperty(key, AIThemes[key])
}
}
// eslint-disable-next-line
}, [])
return (
<Router>
<NavWrapper />
<Routes>
<Route exact path="/pipeline" element={<PipelinePage />} />
<Route exact path="/AI" element={<AIPage />} />
<Route exact path="/bridge" element={<BridgePage />} />
<Route exact path="/" element={<AIPage />} />
</Routes>
</Router>
)
};
export default BasicRoute;
package.json
"react": "^18.1.0",
"react-router-dom": "^6.3.0",
After the configuration is complete, I have no problem entering the address in the address bar to access, only using the router to navigate has problems.
Using Navlink and Link
import React, { useEffect, useState } from 'react';
import { Link, useNavigate, Navigate, BrowserRouter as Router, NavLink } from "react-router-dom";
import styles from "./index.scss";
import aiGray from '#/assets/images/aiGray.png';
import bridgeGray from '#/assets/images/bridgeGray.png';
import caeGray from '#/assets/images/caeGray.png';
import pipeGray from '#/assets/images/pipeGray.png';
import { LinkOutlined } from '#ant-design/icons';
const ActiveTheme = ({ themeName }) => {
/**
* String- themeName 当前主题名,传入值需与allTheme中匹配项的key相同,用以删除切换项
*/
const navigate = useNavigate()
const allTheme = [
{
icon: aiGray,
link: '/AI',
disabled: false,
key: 'AI'
},
{
icon: pipeGray,
link: '/Pipeline',
disabled: false,
key: 'Pipeline'
},
{
icon: bridgeGray,
link: '/',
disabled: true,
key: 'bridge'
},
{
icon: caeGray,
link: '/',
disabled: true,
key: 'cae'
}
]
const [allThemeList, setAllThemeList] = useState(allTheme)
// useEffect(() => {
// allTheme.forEach((item, ind) => {
// if (item.key === themeName) {
// allTheme.splice(ind, 1)
// }
// })
// setAllThemeList(allTheme)
// // eslint-disable-next-line
// }, [themeName])
const linkTo = (item) => {
console.log(9999999999999)
// --disable-ipc-flooding-protection
navigate(item.link)
}
return (
<div className={styles.routerInner}>
{
allThemeList.map((item, ind) => {
return (
<NavLink to='/Pipeline' end>
<div key={item.key} className={styles.themeIcon} >
<img src={item.icon} alt="" />
</div>
</NavLink>
)
})
}
</div>
)
}
export default ActiveTheme;
The page navigates but it is a blank page, the error is as follows:
"A component suspended while responding to synchronous input."
Using Navigate
<Navigate to='/Pipeline' end>
<div key={item.key} className={styles.themeIcon} >
<img src={item.icon} alt="" />
</div>
</Navigate>
The page reports an error and falls into an infinite loop:
Maximum update depth exceeded.
I don't know where I trigger the useState infinite loop. How should I change the dependencies?
Usi useNavigate
const navigate = useNavigate()
return (
<div className={styles.routerInner}>
{allThemeList.map((item, ind) => {
return (
<div key={item.key} className={styles.themeIcon} onClick={navigate(item.link)}>
<img src={item.icon} alt="" />
</div>
)
})}
</div>
)
The page does not report an error but gives a warning:
`"router.ts:11 You should call navigate() in a React.useEffect(), not when your component is first rendered"'.

Having issues in react router & navigation

I have created a navigation drawer which goes something like this,
const Minidrawer = props => {
const itemsList = [
{
text: "Home",
icon: <HomeIcon />,
onClick: () => history.push("/")
},
{
text: "My Cart",
icon: <UserIcon />,
onClick: () => history.push("/auth")
},
{
text: "Register Client",
icon: <GroupAddIcon />,
onClick:() => history.push("/register-client")
},
},
];
return (
<Drawer variant="permanent" open={open}>
<DrawerHeader>
<IconButton onClick={handleDrawerClose}>
{theme.direction === 'rtl' ? <ChevronRightIcon /> : <ChevronLeftIcon />}
</IconButton>
</DrawerHeader>
<Divider />
<List>
{itemsList.map((item, index) => {
const { text, icon, onClick } = item;
return (
<ListItem button key={text} onClick={onClick}>
{icon && <ListItemIcon>{icon}</ListItemIcon>}
<ListItemText primary={text} />
</ListItem>
);
})}
</List>
</Drawer>
)}
export default withRouter(Minidrawer);
As you can see I am exporting this in wrapped withRouter because I'm calling browser router main index file
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import { reducers } from './reducers';
import CssBaseline from '#mui/material/CssBaseline';
import { BrowserRouter as Router } from "react-router-dom";
import App from "./App";
const store = createStore(reducer, enhancer);
const rootElement = document.getElementById("root");
ReactDOM.render(
<React.StrictMode>
<Router>
<CssBaseline />
<Provider store={store}><App />
</Provider>
</Router>
</React.StrictMode>,
rootElement
);
My app file where I am importing all the components
import React from "react";
import { Route, Switch } from "react-router-dom";
import Minidrawer from './components/Drawer/Minidrawer'
import { makeStyles } from '#mui/styles';
import Box from '#mui/material/Box';
import Main from "./components/Main/Main";
import {useSelector} from 'react-redux'
const useStyles = makeStyles({
container: {
display: "flex"
}
});
export default function App() {
const classes = useStyles();
const user = useSelector((state) => state.auth);
return (
<Box sx={{ display: 'flex' }}>
<Minidrawer currUser={user}/>
<Main/>
</Box>
);
}
This is my Main component file
import { styled, useTheme } from '#mui/material/styles';
import Box from '#mui/material/Box';
import Typography from '#mui/material/Typography';
import React from 'react';
import { Switch, Route, useHistory} from "react-router-dom";
import { Grid } from '#mui/material';
import Paper from '#mui/material/Paper';
import useStyles from './styles';
import RoutesMaster from "./RoutesMaster";
const RoutesRender = ({ Routes, Key}) => {
const History = useHistory();
console.log(Routes);
if (Routes.AuthRequired) {
History.push('/auth/login');
return null;
} else {
return <Route exact key={Key} path={Routes.Path} render={(props) => <Routes.Component {...props} />} />;
}
};
const Main = (props) => {
const classes = useStyles();
return (
<Box className={classes.box} sx={{ flexGrow: 1 }}>
<Switch>
{RoutesMaster.map((Routes, Index) => (
<RoutesRender Routes={Routes} Key={Index} />
))}
</Switch>
</Box>
)
}
export default Main;
Route Master file,
import Home from '../Home/Home';
import Auth from '../Auth/Auth';
import RegisterClient from '../RegisterClient/RegisterClient'
const RoutesMaster = [
{
Path: '/',
Component: Home,
Title: 'Home',
AuthRequired: false
},{
Path: '/auth',
Component: Auth,
Title: 'Auth',
AuthRequired: false
},{
Path: '/register-client',
Component: RegisterClient,
Title: 'Register Client',
AuthRequired: false
},
]
export default RoutesMaster;
The issue is ,on first load '/' I am getting rendered Home But when on clicking Button links in Mindrawer I can see above on browser URL is changing but the respective component is not getting rendered only getting blank in place of main component
Also one thing to note console.log(Routes); inside RoutesRender in Main.js fn always logs Home "/" path & blank UI

How to use a hook in React?

I have information in the state (true or false) that I want to display if is true this Navbar component, but when I use the hook, I get an error message:
hook error
My code:
import React from 'react';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'connected-react-router';
import store, { history } from './reduxStore';
import AppRouterContainer from './pages/AppRouterContainer';
import Feedback from './pages/feedback/Feedback';
import Navbar from './components/Navbar/Navbar';
import { useTypedSelector } from '../src/hooks/useTypedSelector';
const isAuth = useTypedSelector((state) => state.auth.isAuth);
const App = () => (
<BrowserRouter>
<Provider store={store}>
<ConnectedRouter history={history}>
<AppRouterContainer />
{isAuth && (
<Navbar />
)}
<Feedback />
</ConnectedRouter>
</Provider>
</BrowserRouter>
);
export default App;
You need to create a wrapper component to have access to store in your context (I think your useTypedSelector() hook needs that access).
You can use hooks only inside a function, not just inside a module.
Check out this example:
import React from 'react';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
import { ConnectedRouter } from 'connected-react-router';
import { useTypedSelector } from '../src/hooks/useTypedSelector';
import Navbar from './components/Navbar/Navbar';
import AppRouterContainer from './pages/AppRouterContainer';
import Feedback from './pages/feedback/Feedback';
import store, { history } from './reduxStore';
const NavbarWrapper = () => {
const isAuth = useTypedSelector((state) => state.auth.isAuth);
if (!isAuth) {
return null;
}
return <Navbar />;
};
const App = () => (
<BrowserRouter>
<Provider store={store}>
<ConnectedRouter history={history}>
<AppRouterContainer />
<NavbarWrapper />
<Feedback />
</ConnectedRouter>
</Provider>
</BrowserRouter>
);
export default App;
Also, I think you should move the NavbarWrapper component to a separate file.

React rendering an unexpected element

EDIT: I imported something wrong :facepalm:
Let me first run down what code ive written to get this output then I will tell you the expected output and what im confused about
App.jsx
import React from "react";
import Home from "./components/pages/HomePage";
import store from "./ducks/store";
import { Provider } from "react-redux";
import { BrowserRouter, Route, Switch } from "react-router-dom";
const App = () => {
return (
<BrowserRouter>
<Provider store={store}>
<Switch>
<Route exact path="/" component={Home} />
</Switch>
</Provider>
</BrowserRouter>
);
};
export default App;
Home.jsx
import React, { useEffect } from "react";
import FlexBox from "../../shared/FlexBox";
import BlogPostList from "./SortSettings";
import { useSelector, useDispatch } from "react-redux";
import { fetchAllBlogs } from "../../../ducks/blogs";
import {
getBlogData,
getBlogPosts,
getBlogTags,
} from "../../../ducks/selectors";
import SpinLoader from "../../shared/SpinLoader";
const Home = () => {
const blogData = useSelector((state) => getBlogData(state));
const blogPosts = useSelector((state) => getBlogPosts(state));
const blogTags = useSelector((state) => getBlogTags(state));
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchAllBlogs());
}, [dispatch]);
// TODO: handle if blogData.requestError comes back as true
if (blogData.isLoading || !blogPosts || !blogTags) {
return (
<FlexBox
alignItems="center"
justifyItems="center"
width="100vw"
height="100vh"
>
<SpinLoader />
</FlexBox>
);
}
return (
<FlexBox height="100vh" width="100vw">
<BlogPostList blogPosts={blogPosts} />
</FlexBox>
);
};
export default Home;
BlogPostList.jsx
import React from "react";
import BlogPost from "./BlogPost";
import FlexBox from "../../shared/FlexBox";
const BlogPostList = ({ blogPosts }) => {
return (
<FlexBox flexDirection="column">
Why in the world is this rendering a SortSettings component AHHHHHH!
</FlexBox>
);
};
export default BlogPostList;
Now my question is this why is it that the Home component is rendering a component as showed here https://gyazo.com/8cac1b28bdf72de9010b0b16185943bb what I would expect the Home component to be rendering is a BlogPostList if anyone has an idea help would be appreciated ive been stuck on this for awhile now (im pretty new so this might just be a noob mistake so sorry if its something obvious)

Categories