React Router With Handler showing blank page - javascript

I'm implementing react application. By the way, I'm encountering react router showing blank page without any error or exception. I have searched through stack overflow and knowing that browse history might be missing. I have no luck still even implemented browseHistory and the page is still showing blank.
Here is my code,
import React from 'react';
import ReactDOM from 'react-dom';
//import App from 'components/App.js';
//import Home from 'components/Home.js';
import injectTapEventPlugin from 'react-tap-event-plugin';
import { Router, Route, IndexRoute, browserHistory, hashHistory, RouteHandler } from 'react-router';
injectTapEventPlugin();
var Home = React.createClass({
render: function() {
return (<h1>Welcome to the Home Page</h1>);
}
});
let App = React.createClass({
render() {
<div className="nav">
<h1>It's work</h1>
<RouteHandler/>
</div>
}
});
let routes = (
<Route name="app" path="/" handler={App} >
<Route name="home" path="/home" handler={Home} />
</Route>
);
ReactDOM.render(<Router routes={routes} history={browserHistory} />, document.getElementById('app'));
Appreciate to somebody's contribution if you have idea about this.
Here is my package json.
{
"name": "finalize",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node server.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.24.0",
"babel-eslint": "^7.2.1",
"babel-loader": "^6.4.1",
"babel-preset-es2015": "^6.24.0",
"babel-preset-react": "^6.23.0",
"babel-preset-stage-0": "^6.22.0",
"eslint": "^3.18.0",
"eslint-plugin-react": "^6.10.3",
"express": "^4.15.2",
"file-loader": "^0.10.1",
"react-hot-loader": "^1.3.1",
"webpack": "^2.3.2",
"webpack-dev-middleware": "^1.10.1",
"webpack-hot-middleware": "^2.17.1"
},
"dependencies": {
"material-ui": "^0.17.1",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"react-router": "^3.0.2",
"react-tap-event-plugin": "^2.0.1"
}
}

Issue is you forgot to use return in App component, App is main component, so if you don't return anything it will always show blank page, use this:
let App = React.createClass({
render: function {
return (
<div className="nav">
<h1>It's work</h1>
<RouteHandler/>
</div>
)
}
});
Instead of handler use component, handler has been deprecated and doesn't supported in v3.x. check this: https://github.com/ReactTraining/react-router/issues/2887
Use it like this:
let App = React.createClass({
render: function() {
return (
<div className="nav">
<h1>It's work</h1>
{this.props.children}
</div>
);
}
});
let routes = (
<Route name="app" path="/" component={App} >
<Route name="home" path="/home" component={Home} />
</Route>
);
ReactDOM.render(<Router routes={routes} history={browserHistory} />, document.getElementById('app'));
Check the doc also they are using component: https://github.com/reactjs/react-router-tutorial/tree/master/lessons/02-rendering-a-route

Related

TypeError: URL is not a constructor while using react-router-dom

I have been working on one of my personal projects which includes use of react-router-dom.I switched from react-router-dom v5 to v6 and errors started popping out .I have used react-router before but the error shown this time is kind of different and not able to debug the thing since a while. Why it is showing this kind of error?
I
here is my App.js
import React, { useState } from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Navbar from "./components/Navbar";
import StreetNode from "./components/StreetNode";
import Nodes from "./components/Nodes";
import { Scheduler } from "./components/Scheduler";
function App() {
return (
<Router>
<Navbar />
<Routes>
{/* <Route path="/" exact component={Nodes} /> */}
<Route path="/" element={<Nodes />} />
<Route path="/node/:id" element={<StreetNode />} />
<Route path="/scheduler" element={<Scheduler />} />
</Routes>
</Router>
);
}
export default App;
index.js
index.js
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { NodeProvider } from "./NodeContext";
ReactDOM.render(
<NodeProvider>
<App />
</NodeProvider>,
document.getElementById("root")
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
reportWebVitals();
package.json
{
"name": "lightitup",
"version": "0.1.0",
"private": true,
"dependencies": {
"#craco/craco": "^6.4.2",
"#date-io/date-fns": "^2.11.0",
"#emotion/react": "^11.4.1",
"#emotion/styled": "^11.3.0",
"#mui/icons-material": "^5.2.0",
"#mui/lab": "^5.0.0-alpha.61",
"#mui/material": "^5.0.2",
"#mui/styles": "^5.0.1",
"#testing-library/jest-dom": "^5.14.1",
"#testing-library/react": "^11.2.7",
"#testing-library/user-event": "^12.8.3",
"axios": "^0.22.0",
"bootstrap": "^5.1.3",
"chart.js": "^3.6.2",
"chartjs-plugin-zoom": "^1.2.0",
"classnames": "^2.3.2",
"date-fns": "^2.27.0",
"react": "^17.0.2",
"react-chartjs-2": "^4.0.0",
"react-dom": "^17.0.2",
"react-google-charts": "^3.0.15",
"react-notifications-menu": "^1.0.6",
"react-router-dom": "^6.4.5",
"react-scripts": "4.0.3",
"web-vitals": "^1.1.2"
},
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"autoprefixer": "^9.8.8",
"postcss": "^7.0.39",
"react-circular-slider-bar": "^1.3.1",
"tailwindcss": "npm:#tailwindcss/postcss7-compat#^2.2.17"
}
}
You must wrap Router with BrowserRouter. I'm not sure if this is because of the error but you must wrap BrowserRouter anyway.

how to generate static file from react js by using vite js

when I generate a static file of react js from vite js it shows just a blank page.
I don't know, Is this happening bcz of vite app, or is something wrong with the package.json configuration?
i also added homepage property in package.json file but same issue
Vite.config.js
import react from '#vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
base:"./"
})
App.js
import {BrowserRouter,Routes,Route} from 'react-router-dom'
import Navbar from './Layouts/Navbar'
import BecomeInfluncer from './Pages/BecomeInfluncer'
import Home from './Pages/Home'
import ErrorPage from './Pages/ErrorPage'
import PrivacyPolicy from './Pages/PrivacyPolicy'
import TermCondition from './Pages/TermCondition'
function App() {
return (
<>
<BrowserRouter>
<Routes>
<Route path='/' element={<Home/>} />
<Route path='/influencer' element={<BecomeInfluncer/>} />
<Route path='/term-condition' element={<TermCondition />} />
<Route path='/privacy-policy' element={<PrivacyPolicy/>} />
<Route path='*' element={<ErrorPage />} />
</Routes>
</BrowserRouter>
</>
)
}
Package.json
{
"name": "azgarty",
"homepage": "/",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"#fortawesome/fontawesome-svg-core": "^6.2.0",
"#fortawesome/free-solid-svg-icons": "^6.2.0",
"#fortawesome/react-fontawesome": "^0.2.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-responsive": "^9.0.0",
"react-router-dom": "^6.4.1",
"react-router-hash-link": "^2.4.3",
"swiper": "^8.4.2"
},
"devDependencies": {
"#types/react": "^18.0.17",
"#types/react-dom": "^18.0.6",
"#vitejs/plugin-react": "^2.1.0",
"autoprefixer": "^10.4.12",
"postcss": "^8.4.17",
"tailwindcss": "^3.1.8",
"vite": "^3.1.0"
}
}

ReactJS props aren't being passed to other component when navigating?

So in my app I have a login-component and an authenticator-component. The last one works with QR code authorization etc.
Since the package "node-sass" is deprecated now, I changed to the "sass" NPM package. I had to upgrade "react-router" and "react-router-dom" as well to their latest version (6...).
Here's my dependencies:
"dependencies": {
"#material-ui/core": "^4.11.0",
"#material-ui/icons": "^4.9.1",
"#material-ui/lab": "^4.0.0-alpha.56",
"#react-pdf/renderer": "^1.6.12",
"#reduxjs/toolkit": "^1.4.0",
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.5.0",
"#testing-library/user-event": "^7.2.1",
"axios": "^0.20.0",
"caniuse-lite": "^1.0.30001197",
"moment": "^2.29.1",
"qrcode.react": "^1.0.0",
"qs": "^6.9.4",
"react": "^16.13.1",
"react-async": "^10.0.1",
"react-dom": "^16.13.1",
"react-fade-in": "^1.1.0",
"react-icons": "^3.11.0",
"react-movable": "^2.5.3",
"react-outside-click-handler": "^1.3.0",
"react-qr-reader": "^2.2.1",
"react-redux": "^7.2.1",
"react-router": "^6.0.2",
"react-router-dom": "^6.0.2",
"react-scripts": "3.4.3",
"redux": "^4.0.5",
"redux-axios-middleware": "^4.0.1",
"redux-devtools-extension": "^2.13.8",
"redux-thunk": "^2.3.0",
"sass": "^1.43.4",
"xlsx": "^0.16.8"
},
So my next step was to change everything from "react-router" and "react-router-dom" to use their latest items, like "useHistory" was changed to "useNavigate" etc.
Their "history.push("/route")" was also changed to "navigate("/route")" now, so I changed those as well.
And lastly, they removed the "withRouter" function from their package, which used to be required for navigation to work inside main App. It used to be like this:
export default withRouter(App);
But now this is the hook that it replaces:
import React from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
export const withRouter = (Component) => {
const Wrapper = (props) => {
const navigate = useNavigate();
const location = useLocation();
return (
<Component
{...props}
navigate={navigate}
location={location}
/>
);
};
return Wrapper;
};
And then you import that one, and use "withRouter(App)" etc...
Here's (part of) my App Routing:
return (
<ThemeProvider theme={theme}>
<Loading />
<Header
menuHandler={() => {
changeMenu(!showMenu);
}}
setActive={setActive}
/>
<main className="main">
<MenuBar
showMenu={showMenu}
toggleMenu={() => changeMenu(!showMenu)}
active={active}
setActive={setActive}
/>
<Container className="main__container" id="main__container">
<MySnackbar />
<Modal />
<Routes>
<Route
path="/scanner"
element={
<ScannerScreen />
}
/>
<Route
path="/authenticator"
element={
<Authenticator />
}
/>
<Route
path="/login"
element={
<Login />
}
/>
...
As you can see, where it says now "Routes" is where it used to say "Switch" in previous "react-router-dom" versions.
I used to navigate between pages, like so:
import { useNavigate } from "react-router-dom";
...
const navigate = useNavigate();
...
navigate("/authenticator", {
authMode: "login",
username: user.username,
});
As you can see, I'm using the V6 "navigate" from "react-router-dom" now instead of the previous "history.push('/authenticator')" for example.
This navigation works, however no props are passed (like authMode & username) and the props are always "undefined" in the target/new component, when here/source component they are filled in.
No matter what I do, props are always undefined, like so:
// both authMode & username will be undefined
const Authenticator = ({ authMode, username }) => {...}
// props will be undefined
const Authenticator = (props) => {...}
// both of these will return undefined values
const Authenticator = () => {
const { authMode, username } = useParams();
const { authMode, username } = useLocation();
}
Does anyone have any idea how I can properly pass props from Login to my Authenticator, using Javascript, like so:
navigate("/authenticator", {
authMode: "login",
username: user.username,
});
Thanks!
So, of course, right after posting a stackoverflow post I kept on digging and finally found "a" solution myself. I'm not sure if this is the best way, but here it is.
Looking at this post: https://stackoverflow.com/a/64566486/3384458 , props are no longer "just" passed to other components. It has to go via the "location" prop now.
So now I have to do it like this, in my Login-component:
navigate("/authenticator", {
state: {
authMode: "login",
username: user.username,
}
});
You have to set the "location.state" prop of "location", like above.
Now the "location.state" prop will contain my object with "authMode" and "userName".
In my Authenticator-component, I do it like this now:
const { authMode, username } = useLocation().state;
Here's another helpful link for react-router v6: https://remix.run/blog/react-router-v6

React router dom is working for some component but not working for another component

My problem is that react-router-dom is working for Homepage and productList but not working for Signin component. I think there is no problem with snowpack. But I put snowpack config file, in case there is some problem. The weird thing is I added a Header for Homepage and product list but I didn't added the header for Signin component. but after changing the route, header is showing even I didn't add Header into the Signin Component. I am so confused that why this is happening.
App.jsx
import React from 'react';
import Homepage from './Containers/Homepage';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import ProductList from './Containers/ProductList';
import Signin from './Containers/Signin';
function App() {
return (
<div className="App">
<Router>
<Switch>
<Route path="/" exact component={Homepage} />
<Route path="/:slug" component={ProductList} />
<Route exact path="/signin" component={Signin} />
</Switch>
</Router>
</div>
);
}
export default App;
Signin.jsx
import { Typography } from '#material-ui/core';
import React from 'react';
import Layout from '../Components/Layout';
const Signin = () => {
return (
<div
style={{
marginTop: '10rem',
paddingTop: '10rem',
background: 'black',
height: '100vh',
}}
>
Signin
</div>
);
};
export default Signin;
Header.jsx
this file is big. but I'm adding the route call.
const handleButtonClick = (pageURL) => {
history.push(pageURL);
};
<Button variant="contained" onClick={() => handleButtonClick('/signin')}>
Login
</Button>;
snowpack.config.js
/** #type {import("snowpack").SnowpackUserConfig } /
module.exports = {
mount: {
/ ... /
public: "/",
src: "/dist",
},
plugins: ["#snowpack/plugin-react-refresh"],
routes: [
{ match: "all", src: "/api/.", dest: (req, res) => proxy.web(req, res) },
{ match: "routes", src: ".", dest: "/index.html" },
],
optimize: {
/ Example: Bundle your final build: /
// "bundle": true,
},
packageOptions: {
polyfillNode: true,
},
devOptions: {
port: 3000,
},
buildOptions: {
/ ... */
},
};
package.json
{
"name": "ecommerce-website",
"version": "0.1.0",
"private": true,
"dependencies": {
"#material-ui/core": "^4.11.4",
"#material-ui/icons": "^4.11.2",
"#snowpack/plugin-webpack": "^2.3.1",
"#testing-library/jest-dom": "^5.12.0",
"#testing-library/react": "^11.2.6",
"#testing-library/user-event": "^12.8.3",
"axios": "^0.21.1",
"formik": "^2.2.6",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-icons": "^4.2.0",
"react-query": "^3.13.12",
"react-router": "^5.2.0",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"web-vitals": "^1.1.2",
"yup": "^0.32.9"
},
"scripts": {
"start": "snowpack dev",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": ["react-app", "react-app/jest"]
},
"browserslist": {
"production": [">0.2%", "not dead", "not op_mini all"],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#snowpack/plugin-react-refresh": "^2.5.0",
"snowpack": "^3.3.7"
}
}
Any help will be appreciated before I punch my Laptop Screen. Thanks.
The problem is with
<Route path="/:slug" component={ProductList} />
<Route exact path="/signin" component={Signin} />
/:slug as first route accepts everything and renders the productList on every request other than / Homepage because of the exact attribute.
You can interchange its position with the signIn component to get the correct Component Rendering. Like this
<Route exact path="/signin" component={Signin} />
<Route path="/:slug" component={ProductList} />
This route:
<Route path="/:slug" component={ProductList} />
Is a match for /signin, where signin is treated as the parameter :slug. In fact, this route will match pretty much any path except /, because you don't have an exact prop. The path /a/b/c/d is a match, where a is the parameter :slug.
I would restructure the switch to look like this:
<Switch>
<Route path="/" exact component={Homepage} />
<Route exact path="/signin" component={Signin} />
<Route path="/:slug" component={ProductList} />
</Switch>
It will now choose the first matching path, which is your static route. I would also potentially make the /:slug path exact as well if you are not expecting to match all paths here.

How to fix: Warning: Functions are not valid as a React child

I've updated my router to take in a second main route.
import React from 'react';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
// Containers & Pages
// Home
import HomePage from '/imports/ui/pages/home/HomePage.js';
// Accounts
import SignUp from '/imports/ui/pages/accounts/SignUp.js';
import Login from '/imports/ui/pages/accounts/Login.js';
import ForgotPassword from '/imports/ui/pages/accounts/ForgotPassword.js';
import ResetPassword from '/imports/ui/pages/accounts/ResetPassword.js';
import PaymentPage from '/imports/ui/pages/accounts/PaymentPage.js';
import CouponPaymentPage from '/imports/ui/pages/accounts/CouponPaymentPage.js';
import AccountPage from '/imports/ui/pages/accounts/AccountPage.js';
// General
import AppContainer from '/imports/ui/containers/AppContainer.js';
// In App
import DashboardContainer from '/imports/ui/containers/app/DashboardContainer.js';
import AllRecipesContainer from '/imports/ui/containers/app/AllRecipesContainer.js';
// Legal
import PrivacyPage from '/imports/ui/pages/legal/PrivacyPage.js';
import TermsPage from '/imports/ui/pages/legal/TermsPage.js';
import DisclaimersPage from '/imports/ui/pages/legal/DisclaimersPage.js';
// Admin
import AdminContainer from '/imports/ui/containers/AdminContainer.js';
import UsersAdminContainer from '/imports/ui/containers/UsersAdminContainer.js';
import RecipeStatsPage from '/imports/ui/pages/admin/RecipeStatsPage.js';
// Routes
export const renderRoutes = () => (
<Router onUpdate={() => window.scrollTo(0, 0)} history={browserHistory}>
<Route path="/" component={AppContainer}>
<IndexRoute name="Home" component={HomePage} />
<Route name="Sign Up" path="/signup" component={SignUp} />
<Route name="Log In" path="/login" component={Login} />
<Route name="Forgot Password" path="/forgotpassword" component={ForgotPassword} />
<Route name="Reset Password" path="/reset-password/:token" component={ResetPassword} />
<Route name="Coupon Payment Page" path="/coupons/:code" component={CouponPaymentPage} />
<Route name="Privacy Page" path="/privacy" component={PrivacyPage} />
<Route name="Terms" path="/terms" component={TermsPage} />
<Route name="Disclaimers" path="/disclaimers" component={DisclaimersPage} />
<Route name="Payment" path="/payment" component={PaymentPage} />
<Route name="Dashboard" path="/dashboard" component={DashboardContainer} />
<Route name="Browse All Recipes" path="/browseall" component={AllRecipesContainer} />
<Route name="Manage Account" path="/account" component={AccountPage} />
</Route>
<Route path="/manager" component={AdminContainer}>
<IndexRoute name="manager home" component={UsersAdminContainer} />
<Route path="/manager/recipes" component={RecipeStatsPage} />
</Route>
</Router>
);
When I navigate to '/manager' in my app I get an error:
Warning: Functions are not valid as a React child. This may happen if
you return a Component instead of from render. Or maybe
you meant to call this function rather than return it.
in Unknown (created by RouterContext)
in RouterContext (created by Router)
in Router
// AdminContainer.js
import { Meteor } from 'meteor/meteor';
import { withTracker } from 'meteor/react-meteor-data';
import Admin from '/imports/ui/layouts/Admin.js';
export default withTracker(() => {
const userHandle = Meteor.subscribe('users.myData');
const loading = !userHandle.ready();
return {
user: Meteor.user(),
loading,
};
}, Admin);
// UsersAdminContainer.js
import { Meteor } from 'meteor/meteor';
import { withTracker } from 'meteor/react-meteor-data';
import UsersAdminPage from '/imports/ui/pages/admin/UsersAdminPage.js';
export default withTracker(() => {
const usersHandle = Meteor.subscribe('users.allUsers');
const loading = !usersHandle.ready();
return {
loading,
users: Meteor.users.find().fetch(),
};
}, UsersAdminPage);
I've tried importing the UsersAdminPage and using that for the component of the indexroute. I've looked at this answer on SO (Functions are not valid as a React child. This may happen if you return a Component instead of from render). I'm not seeing my error any help would be much appreciated.
// package.json
{
"name": "-",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "meteor --settings dev-settings.json"
},
"dependencies": {
"autoprefixer": "^7.1.1",
"babel-runtime": "^6.26.0",
"bcrypt": "^1.0.3",
"bluebird": "^3.5.1",
"contentful": "^5.1.3",
"marked": "^0.3.6",
"meteor-node-stubs": "~0.2.4",
"moment": "^2.21.0",
"prop-types": "^15.6.0",
"radium": "^0.19.6",
"react": "^16.1.1",
"react-async-script-loader": "^0.3.0",
"react-burger-menu": "^2.1.11",
"react-document-title": "^2.0.3",
"react-dom": "^16.1.1",
"react-feather": "^1.0.7",
"react-flatpickr": "^3.6.3",
"react-router": "^3.0.5",
"react-stripe-elements": "^1.2.1",
"react-tooltip": "^3.4.0",
"reactable": "github:vladnicula/reactable",
"sib-api-v3-sdk": "^3.1.6",
"simpl-schema": "^0.3.2",
"stripe": "^5.5.0",
"sweetalert": "^2.0.8",
"sweetalert2": "^7.1.2",
"underscore": "^1.8.3"
},
"devDependencies": {
"#meteorjs/eslint-config-meteor": "^1.0.5",
"babel-eslint": "^7.2.3",
"eslint": "^4.4.1",
"eslint-config-airbnb": "^15.1.0",
"eslint-import-resolver-meteor": "^0.4.0",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-jsx-a11y": "^5.1.1",
"eslint-plugin-meteor": "^4.0.1",
"eslint-plugin-react": "^7.2.1"
},
"postcss": {
"plugins": {
"postcss-easy-import": {
"extensions": [
".css",
".scss",
".import.css"
]
},
"autoprefixer": {
"browsers": [
"last 2 versions"
]
}
}
},
"eslintConfig": {
"parser": "babel-eslint",
"parserOptions": {
"allowImportExportEverywhere": true,
"allowAfterThis": true
},
"plugins": [
"meteor"
],
"extends": [
"airbnb",
"plugin:meteor/recommended"
],
"settings": {
"import/resolver": "meteor"
},
"rules": {
"import/extensions": [
"off",
"never"
],
"import/no-extraneous-dependencies": "off",
"import/prefer-default-export": "off",
"import/no-absolute-path": "off",
"react/prefer-stateless-function": "off",
"react/jsx-filename-extension": "off",
"react/forbid-prop-types": "off",
"react/require-default-props": "off",
"no-underscore-dangle": "off",
"jsx-a11y/no-static-element-interactions": "off",
"class-methods-use-this": "off"
}
}
}
Your calls to withTracker are incorrect. They should pass the component to the result of withTracker:
export default withTracker(() => {
const userHandle = Meteor.subscribe('users.myData');
const loading = !userHandle.ready();
return {
user: Meteor.user(),
loading,
};
})(Admin);
Relevant docs here.

Categories