React code-splitting eror. Page is not displayed - reactjs

I have used code-splitting using React lazy. No errors are showed, but the page is not displayed. The following code is inside the index.js
What am I doing wrong?
import React from "react";
import "./index.css";
import * as serviceWorker from "./serviceWorker";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import {Suspence,lazy} from 'react';
// Imported Pages
const HomePage = lazy(() => import("./components/home_page/index"));
const MoviePage = lazy(() => import("./components/movie_page/index"));
const App = () =>(
<Router>
<Suspence falback ={<div>Loading...</div>}>
<Switch>
<Route exact path="/" component={HomePage} />
<Route exact path="/movie_page" component={MoviePage}/>
</Switch>
</Suspence>
</Router>,
document.getElementById("root")
);
serviceWorker.unregister();
export default App

Related

React Router not loading component

I am relatively new to React and can't for the life of me figure out why this isn't working!
This code is not loading the App component inside router, but it does when returned independently. Example below
import React from "react";
import ReactDOM from "react-dom";
import App from "../components/App";
import { Router, Route } from "react-router-dom";
document.addEventListener("DOMContentLoaded", () => {
ReactDOM.render(
<Router>
<Route path="/">
<App />
</Route>
</Router>,
document.body.appendChild(document.createElement("div"))
);
});
Nothing loads on the screen with this. However when I remove the router I see the App component load:
import React from "react";
import ReactDOM from "react-dom";
import App from "../components/App";
import { Router, Route } from "react-router-dom";
document.addEventListener("DOMContentLoaded", () => {
ReactDOM.render(
<App />,
// <Router>
// <Route path="/">
// <App />
// </Route>
// </Router>,
document.body.appendChild(document.createElement("div"))
);
});
Finally, this is my App component (dont think you need this though)
import React from "react";
const App = () => {
return <div>app has loaded</div>;
};
export default App;
This is built on a Ruby on Rails app, if that matters
if you'are using react-router-dom v5:
import React from "react";
import ReactDOM from "react-dom";
import App from "../components/App";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
document.addEventListener("DOMContentLoaded", () => {
ReactDOM.render(
<Router>
<Switch>
<Route path="/">
<App />
</Route>
</Switch>
</Router>,
document.body.appendChild(document.createElement("div"))
);
});
if you're using react-router-dom v6
import React from "react";
import ReactDOM from "react-dom";
import App from "../components/App";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
document.addEventListener("DOMContentLoaded", () => {
ReactDOM.render(
<Router>
<Routes>
<Route path="/" element={<App />} />
</Routes>
</Router>,
document.body.appendChild(document.createElement("div"))
);
});
Instead of
import { Router, Route } from "react-router-dom";
try
import { BrowserRouter, Route } from "react-router-dom";
What versions of react and react-router-dom are you using? This works for me in a fresh npx create-react-app:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { BrowserRouter, Routes, Route } from "react-router-dom"; // BrowserRouter as Router
document.addEventListener("DOMContentLoaded", () => {
ReactDOM.render(
<div>
<BrowserRouter>
<Routes>
<Route path="/" element={<App />} />
</Routes>
</BrowserRouter>
</div>,
document.body.appendChild(document.createElement("div"))
);
});
Fixed:
import React from "react";
import ReactDOM from "react-dom";
import App from "../components/App";
import { Router, Route, Switch } from "react-router-dom";
document.addEventListener("DOMContentLoaded", () => {
ReactDOM.render(
<Router>
<Switch>
<Route exact path="/">
<App />
</Route>
</Switch>
</Router>,
document.body.appendChild(document.createElement("div"))
);
});
If you have followed all the steps, then the answer may just be that you installed the NPM package in the wrong place.
Make sure it is in your project folders JSON file.
Considering you're new to React it is pretty easy to install packages in the wrong place.

React Router with custom history not working

When I was using BrowserRouter from react-router-dom, My Routes were working. But to use custom history, I replaced BrowserRouter with Router from react-router. After that my Route components are not loading properly but the url is changing properly.
Here is my codes:
AppRouter-JS:----
import React from 'react';
import { Router, Route, Switch} from 'react-router';
// import { BrowserRouter as Router,Route, Switch} from 'react-router-dom';
import {createBrowserHistory} from 'history'
import Header from '../components/Header.js';
import Dashboard from '../components/DashboardPage.js'
import CreateExpense from '../components/CreateExpensePage.js';
import EditExpense from '../components/EditExpensePage.js';
import Help from '../components/HelpPage.js';
import PageNotFound from '../components/PageNotFound.js'
import LoginPage from '../components/LoginPage.js'
export const history = createBrowserHistory();
const AppRouter = ()=>(
<Router history={history}>
<div>
<Header/>
<Switch>
<Route path='/' exact={true} component={LoginPage}/>
<Route path='/dashboard' component={Dashboard}/>
<Route path='/create' component={CreateExpense} />
<Route path="/edit/:id" component={EditExpense}/>
<Route path='/help' component={Help} />
<Route component={PageNotFound}/>
</Switch>
</div>
</Router>
)
export default AppRouter;
HeaderJS:-- (Here we have the NavLinks)
import React from 'react';
import {NavLink, Link} from 'react-router-dom';
import {connect} from 'react-redux';
import {LogoutAction} from '../Redux/Actions/AuthActions.js'
export const Header = ({logoutAction})=>(
<header>
<h1>Expense Tracker</h1>
<p><NavLink exact activeClassName='active-class' to='/'>Home Page</NavLink></p>
<p><NavLink activeClassName='active-class' to='/create'>Add Expense</NavLink></p>
<p><NavLink activeClassName='active-class' to='/help'>Help Page</NavLink></p>
<button onClick={logoutAction}>Logout</button>
</header>
);
const mapDispatchToProps = (dispatch)=> {
return {
logoutAction: ()=> dispatch(LogoutAction())
}
}
export default connect(undefined,mapDispatchToProps) (Header);
After clicking any NavLink or Link it always opens the PageNotFound component.
I actually just found my problem, and it might be yours too.
I was on react-router-dom#5.2.0 and history#5.0.0.
react-router 5x is compatible with history 4x. Once I downgraded to history#4.10.1 everything started working.
Now using useNavigate() hook instead of useHistory() or anything related to history.
You can use like this;
import { useNavigate } from "react-router-dom";
let navigate = useNavigate();
navigate('/detail')
Note:Written to update information.
i used history.goBack("/signup") not history.push("/signup") seems to work for me .

React router changes url but not page loading

// this is my index.js
import React, { } from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import store from "./store/configureStore";
import { Router } from "react-router";
import "./index.css";
import App from "./App";
import history from "./history";
// append app to dom
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<App />
</Router>
</Provider>,
document.getElementById("root")
);
//this is my app.js
import React, { Component } from 'react';
import { Route, Switch, BrowserRouter } from 'react-router-dom';
import Inscription from "../src/pages/inscription";
class App extends Component {
render() {
return (
< BrowserRouter>
<Route exact path="/" component={Inscription} />
</ BrowserRouter>
);
}
}
export default (App);
I am having changing the view in react with routing. It seems I have tried everything I can google with no luck. the page affiche but doesn't load
Please same one can help mee :(
Try removing the BrowserRouter from the App component. You have already provided a Router in index.js. Also in case you want to define multiple routes, you have to use switch
<Switch>
<Route exact path="/" component={Inscription} />
<Route exact path="/hello" component={HelloComponent} />
<Switch>

React - Migrating to React Router 4

I am in the process of migrating my React App from React-Router-3 to React-Router-4 and I am having a few issues. The layout of my application is as follows.
build
node_modules
public
src
AboutScreen
ContactScreen
HomeScreen
LoginScreen
SignUpScreen
WorkRequestScreen
App.js
index.js
routes.js
serviceWorker.js
package.json
package-lock.json
I am getting the following error:
./src/index.js: Line 8: Unexpected use of 'history' no-restricted-globals
When I remove the history={history} from index.js, I get the following error.
TypeError: Cannot read property 'location' of undefined
I have been following the following tutorial to migrate from 3 to 4.
https://codeburst.io/react-router-v4-unofficial-migration-guide-5a370b8905a
My route.js looks like this:
import React from 'react';
import { Route, Redirect, Router, Switch } from 'react-router-dom';
import createHashHistory from 'history/createHashHistory';
import App from './App';
import Home from './HomeScreen/Home';
import WorkReq from './WorkRequestScreen/WorkReq';
import About from './AboutScreen/About';
import Contact from './ContactScreen/Contact';
import Login from './LoginScreen/Login';
import Signup from './SignUpScreen/Signup';
const history = createHashHistory();
const routes = () => (
<Router history={history}>
<Switch>
<Route exact path="/workReq" component={WorkReq}/>
<Route exact path="/about" component={About}/>
<Route exact path="/contact" component={Contact}/>
<Route exact path="/login" component={Login}/>
<Route exact path="/signup" component={Signup}/>
<Route exact path="/" component={Home}/>
</Switch>
</Router>
);
export default routes;
My index.js looks like this:
import React from 'react';
import ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';
import { Route, Redirect, Router, Switch } from 'react-router-dom';
import routes from './routes';
ReactDOM.render(<Router history={history} routes={routes}/>,
document.getElementById('root'));
serviceWorker.unregister();
Passing history explicitly isn't required as Route is passed history implicitly as prop. 1
I'd remove history prop passed to Router from the index.js and also remove it from Router in routes.js

getting 404 error in react-router-dom

I have started with react-router-dom. my main page rendered successfully but when I am clicking on hyper provided by Link component it is not redirecting but if I hit url manually it is giving me 404 error. please help me in this?
here is my config file
import React from 'react'
import { render } from 'react-dom'
import { createStore, applyMiddleware,compose } from 'redux'
import { Provider } from 'react-redux'
//import rootReducer from './reducers'
import createLogger from 'redux-logger'
import thunk from 'redux-thunk'
import {BrowserRouter} from 'react-router-dom'
import promise from "redux-promise-middleware"
import logger from "redux-logger"
import {fetchUsers} from "./action/UserAction"
import {fetchChart} from "./action/ChartAction"
import {fetchNames} from "./action/SearchAction"
import reducer from "./reducers"
import routes from "./routes"
const middleware = applyMiddleware(promise(), thunk, logger())
const store= createStore(reducer,middleware)
store.dispatch(fetchUsers());
store.dispatch(fetchChart());
render(
<Provider store={store}>
<BrowserRouter >
{routes}
</BrowserRouter>
</Provider>,
document.getElementById('root')
)
my routes file
import App from "./pages/App"
import Users from "./pages/Users"
import Charts from "./pages/Charts"
import React from "react"
import { Route } from "react-router-dom"
export default (
<switch>
<Route path="/" component={App}/>
<Route path="/users" component={Users}/>
<Route path="/charts" name="charts" component={Charts}/>
</switch>
);
App.js
import {Link} from "react-router-dom"
import React from "react"
const App = () =>(
<div>
<h1> this is main page </h1>
<Link to="charts">charts</Link>
</div>
)
export default App
Users.js
import React from "react"
const User = () =>(
<div>
<h1> this is user </h1>
</div>
)
export default User
Charts.js
import React from "react"
const Chart = () => (
<h1> this is chart </h1>
)
export default Chart
UPDATE 1:
I do not know what is going on. but I alter the sequence in routes.js it is working by clicking on url. but still if I hit the url manually or refresh there it is still not working. below is my updated routes.js
import App from "./pages/App"
import Users from "./pages/Users"
import Charts from "./pages/Charts"
import React from "react"
import { Route,Switch } from "react-router-dom"
export default (
<Switch>
<Route path="/charts" component={Charts}/>
<Route path="/users" component={Users}/>
<Route path="/" component={App}/>
</Switch>
);
UPDATE 2:
if I am using exact path then sequence does not matter. I think I didn't understand use of exact path correctly. but still while hitting url manually or refreshing is not working for me
my final routes.js
import App from "./pages/App"
import Users from "./pages/Users"
import Charts from "./pages/Charts"
import React from "react"
import { Route,Switch } from "react-router-dom"
export default (
<Switch>
<Route exact path="/" component={App}/>
<Route exact path="/charts" component={Charts}/>
<Route exact path="/users" component={Users}/>
</Switch>
);
After struggling I got a SO post saying that if my data is not mapping from backend I should use HashRouter. So I changed my browser so I changed my code to this. but I don't know why browser router didn't work
<Provider store={store}>
<HashRouter >
{routes}
</HashRouter>
</Provider>,
document.getElementById('root')
If you are using webpack add this
devServer: {
historyApiFallback: true,
}
when using BrowserRouter "historyApiFallback" should be true

Resources