react router 4 nested components not working properly - javascript

I am switching from react-router 3.x to 4.x and I am not able to render nested routes.
I bootstrapped an application using create-react-app
index.js file
import React from 'react';
import ReactDOM from 'react-dom';
import Routes from './routes';
import './index.css';
ReactDOM.render(<Routes />, document.getElementById('root'));
routes.js file
import React from 'react';
import _ from 'lodash';
import {
BrowserRouter as Router,
Route,
} from 'react-router-dom';
import { dojoRequire } from 'esri-loader';
import EsriLoader from 'esri-loader-react';
import App from './components/App';
import Home from './components/Home';
/**
* Helper component to wrap app
*/
class AppWrapper extends React.Component {
/**
* Util function to render the children
* Whenever a state change happens in react application, react will render the component again
* and we wish to pass the updated state to the children as props
*/
renderChildren() {
const {children} = this.props;
if (!children) {
return;
}
return React.Children.map(children, c => React.cloneElement(c, _.omit(this.props, 'children'), { }));
}
render() {
const child = this.renderChildren();
return (
<App {...this.props}>
{child}
</App>
);
}
}
/**
* Root Loader component to load esri api
*/
class LoaderComponent extends React.Component {
constructor(props) {
super(props);
this.state = { loaded: false };
}
/**
* Callback fired when arc GIS api is loaded
* Now load the requirejs modules using dojorequire
*/
esriReady() {
dojoRequire(['esri/Map', 'esri/views/MapView'], (Map, MapView) => {
this.setState({ Map, MapView, loaded: true });
});
}
render() {
const options = {
url: 'https://js.arcgis.com/4.3/',
};
return (
<div>
<EsriLoader options={options} ready={this.esriReady.bind(this)} />
<AppWrapper {...this.state}>
<Route exact path="/home" component={Home} />
</AppWrapper>
</div>
);
}
};
const Routes = (props) => (
<Router {...props}>
<Route exact path="/" component={LoaderComponent} />
</Router>
);
export default Routes;
App and home components are simple div tags that renders <div>Hello world App</div> and <div>Hello world Home</div>
The App component renders perfectly, but when I navigate to http://localhost:3000/home component I see an empty page.
What I would like to do is
When the user launched the app the user should be redirected to /home and I would like to define two additional routes for App Component
<Route exact path="/a" component={A} />
<Route exact path="/b" component={B} />
Currently I am not able to redirect to /home on app load and not able to define nested routes for App Component.
NOTE: This above code was working fine for react-router version 3.x. To redirect on page load I would use IndexRedirect.
I already had a look at this and this question and I tried all possible solutions in those questions but none is working.
I would like to have all the route handling in routes.js file.

You could achieve such routing with Switch and Redirect:
import React from 'react';
import {Route, Switch, Redirect} from 'react-router-dom';
import {LoaderComponent, AppWrapper , Home, A, B} from './mycomponents';
const routes = (
<LoaderComponent>
<AppWrapper>
<Switch>
<Route exact path='/' render={() => <Redirect to='/home' />} />
<Route exact path='/home' component={Home} />
<Route exact path='/a' component={A} />
<Route exact path='/b' component={B} />
</Switch>
</AppWrapper>
</LoaderComponent>
);
export default routes;
And use the routes.js file something like this:
import React from 'react';
import {render} from 'react-dom';
import {Router} from 'react-router-dom';
import createHistory from 'history/createBrowserHistory';
import routes from './routes';
const history = createHistory();
const App = () =>
<Router history={history}>
{routes}
</Router>;
render(<App />, document.getElementById('root'));

Hey I have implemented react-router-v4, for a simple sample project. here is the github link : How to Implement the react-router-v4. please go through it. very simple.
to run : clone it and hit npm install. hope this will help to you.

Related

React-router <Route> tag not rendering component

I'm running into an issue where my route tag in specific is not rendering any components.
Steps I have tried:
Changed import of { Route } from "react-router-dom".
Changed paths to see if other paths render.
Rendered the component within tags (this worked).
The issue seems to be coming down to something going on with the tag.
Here is a copy of my code:
import { Component } from "react";
//import all components rendered
import NavBar from "./Nav";
import Orders from "./Orders";
import Cart from "./Cart";
import Menu from "./Menu";
import Login from "./Login.jsx";
import Home from "./Home.jsx";
// for routing
import { Route } from "react-router";
import { BrowserRouter } from "react-router-dom";
//main App to combine all components and be rendered
class App extends Component {
render() {
return (
<BrowserRouter>
<NavBar />
<Route path="/" exact component={Login} />
</BrowserRouter>
)
}
}
export default App;
The versions are:
├─┬ react-router-dom#6.2.1
│ └── react-router#6.2.1 deduped
└── react-router#6.2.1
I tried changing the tags to as per a suggestion and it still didn't work, but I may have implemented it incorrectly. Here is what I tried:
import { Component } from "react";
//import all components rendered
import NavBar from "./Nav";
import Orders from "./Orders";
import Cart from "./Cart";
import Menu from "./Menu";
import Login from "./Login.jsx";
import Home from "./Home.jsx";
// for routing
import { Route } from "react-router";
import { BrowserRouter, Routes } from "react-router-dom";
//main App to combine all components and be rendered
class App extends Component {
render() {
return (
<Routes>
<NavBar />
<Route path="/" exact component={Login} />
</Routes>
)
}
}
export default App;
The errors I am getting on the console are:
Uncaught Error: useRoutes() may be used only in the context of a <Router> component.
Choo 3
React 17
Choo 2
Webpack 3
The above error occurred in the <Routes> component:
Routes#http://localhost:3000/static/js/bundle.js:54433:7
App#http://localhost:3000/static/js/bundle.js:42:1
Any help would be greatly appreciated!
Solution:
Was resolved by switching the "component" tag to "element" tag and removing the tag outside as follows:
<>
<NavBar />
<Routes>
<Route path="/" exact element={<Login />} />
</Routes>
</>
List item
put Navbar outside for Routes tag like i did below
import { BrowserRouter, Routes,Route } from "react-router-dom";
//main App to combine all components and be rendered
class App extends Component {
render() {
return (
<>
<NavBar />
<Routes>
<Route path="/" element={<Login/>} />
</Routes>
</>
)
}
}
export default App;
also for newer version of react-router-dom use element instead of component and remove exact
It will be good if you use BrowserRouter index.js and wrapper App over there
for example index.js
<BrowserRouter><App/></BrowserRouter>
I ran into the same issue on react router v6, you need to wrap all your routes in the Routes component from react-router-dom.
Try this:
import { Component } from "react";
//import all components rendered
import NavBar from "./Nav";
import Orders from "./Orders";
import Cart from "./Cart";
import Menu from "./Menu";
import Login from "./Login.jsx";
import Home from "./Home.jsx";
// for routing
import { BrowserRouter, Route, Routes } from "react-router-dom";
//main App to combine all components and be rendered
class App extends Component {
render() {
return (
<BrowserRouter>
<NavBar />
<Routes>
<Route path="/" element={<Login/>} exact/>
</Routes>
</BrowserRouter>
)
}
}
export default App;

React app routing doesn't load content unless page reloaded

I've been working on a react single page app and have been trying to get the routing to work.
I believe the routing itself actually works however the page does not load the correct content unless the page is manually reloaded. Back and forward browser arrows also work.
For example I can navigate to localhost:3000 fine and the content is loaded correctly but when I press a button to navigate to localhost:3000/contacts nothing is displayed unless I refresh the page. Once manually refreshed the contacts page shows up. What gives?
index.tsx
import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router } from 'react-router-dom';
// Import App component
import App from './App'
// Import service workers
import * as serviceWorker from './serviceWorker'
// Render App component in the DOM
ReactDOM.render(
<Router>
<App />
</Router>
, document.getElementById('root')
)
serviceWorker.unregister()
App.tsx
// Import necessary dependencies
import React from 'react'
import Routes from './Routes'
// Create App component
function App() {
return (
<div className="App">
<Routes />
</div>
)
}
export default App
history.tsx
import { createBrowserHistory as history} from 'history';
export default history();
Home/Home.tsx
import React, { Component } from "react";
import history from './../history';
import "./Home.css";
export default class Home extends Component {
render() {
return (
<div className="Home">
hello home
<button onClick={() => history.push('/Contact')} value='click here'>Get Started</button>
</div>
);
}
}
Contact/Contact.tsx
import React, { Component } from 'react';
class Contact extends Component {
render() {
return (
<div>
hello world
</div>
);
}
}
export default Contact;
Routes.tsx
import React, { Component } from "react";
import {BrowserRouter, Router, Switch, Route } from "react-router-dom";
import Contact from "./Contact/Contact";
import Home from "./Home/Home"
import history from './history'
export default class Routes extends Component {
render() {
return (
<div>
<Router history={history}>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/Contact" component={Contact} />
</Switch>
</Router>
</div>
)
}
}
Any help greatly appreciated
I think there's some extra code that might be causing conflict. You're defining the Router from react-router-dom twice:
Once here, in index.tsx
ReactDOM.render(
<Router> // here
<App />
</Router>
, document.getElementById('root')
)
and then again in Routes.tsx
<Router history={history}> // here
<Switch>
<Route path="/" exact component={Home} />
<Route path="/Contact" component={Contact} />
</Switch>
</Router>
You have to drop one of them, they're probably conflicting each other
Update
In addition to that, I think you should not use the history object directly from your export, but access it through the HOC withRouter. Then, you'd wrap
So you'd do something like this
import React, { Component } from "react";
import { withRouter } from 'react-router-dom'
import "./Home.css";
class Home extends Component {
const { history } = this.props
render() {
return (
<div className="Home">
hello home
<button onClick={() => history.push('/Contact')} value='click here'>Get Started</button>
</div>
);
}
}
export default withRouter(Home)
I think the issue here is that you need to wrap your pages with withRouter() like so:
import React, { Component } from "react";
import history from './../history';
import "./Home.css";
import { withRouter } from 'react-router-dom'; //<---------- add this
class Home extends Component {
render() {
return (
<div className="Home">
hello home
<button onClick={() => history.push('/Contact')} value='click here'>Get Started</button>
</div>
);
}
}
default export withRouter(Home); //<-------------- and add this
You will need to do the same on your Contact page as well.
Why do you have two routers?
I guess you simply need to remove the Router either in index.tsx or in Routes.tsx
According to you file naming I would remove the Router in Routes.tsx
It seems like you are using the history package for navigation. If you are using the react-router v5, then you may have to downgrade the history package to 4.10.1 until the history package developers issue a new release with the fix. As of writing this, the latest release version of history package is v5.0.1, and if you see a new release than this, you can try with that version first to see if it works, before doing the downgrade to 4.10.1
Issue Link -> https://github.com/remix-run/history/issues/804

(ReactJS + Redux) Form not loading when /new is added to url

I am working on a simple React/Redux/Rails project and I am having an issue loading the form. I have a Router set up which holds the routes on my App.js page
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import '../App.css';
import Navbar from '../components/Navbar'
import Home from '../components/Home'
import Games from './Games'
import GamesShow from './GamesShow';
import GameForm from './GameForm';
class App extends Component {
render() {
return (
<Router>
<div>
<Navbar />
<Switch>
<Route exact path = '/' component={Home} />
<Route exact path = '/games' component={Games} />
<Route exact path = '/games/:id' component={GamesShow} />
<Route exact path = '/games/new' component={GameForm} />
</Switch>
</div>
</Router>
);
}
}
export default App;
There is a link on another page that goes to /games/new.
<Link to="/games/new" exact>Add a new Game</Link>
The page loads under the url, but the page is black except for the Navbar component. I should mention that I am not even trying to load a form yet, just some sample text. I am importing everything so I know my importing/exporting is not the problem.
import React, { Component } from 'react';
class GameForm extends Component {
render() {
return(
<div>
Add a new game to the List
<form onSubmit={this.handleOnSubmit}>
<div>
<label htmlFor="name">Name:</label>
</div>
</form>
</div>
)
}
}
export default GameForm
Things get weird when I remove new from /games/new and comment out the original games route, it will then load the GameForm Component under the url games, but then I add /new back, it stops working. Now I think that covers everything, but here is my index.js just in case.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './containers/App';
import * as serviceWorker from './serviceWorker';
import {Provider} from 'react-redux'
import store from './store'
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
serviceWorker.unregister();
You need to move '/games/new' above '/games/:id'
Like so:
<Switch>
<Route exact path = '/' component={Home} />
<Route exact path = '/games' component={Games} />
<Route exact path = '/games/new' component={GameForm} />
<Route exact path = '/games/:id' component={GamesShow} />
</Switch>
It needs to come before the dynamic path...

Same component used in multiple routes is being remounted react-router

I created a simple react application. It has a header and three other components called welcome, feature 1 and feature 2.
index.js
import React from 'react'
import { render } from 'react-dom'
import { BrowserRouter, Route } from 'react-router-dom'
import App from './App';
render((
<BrowserRouter>
<Route path="/" component={App} />
</BrowserRouter>
), document.getElementById('root'));
App.js
import React from 'react'
import Header from './Header'
import Main from './Main'
const App = () => (
<div>
<Header />
<Main />
</div>
)
export default App
Header.js
import React, { Component } from 'react';
export default class Header extends Component {
componentDidMount() {
APICall('/user')
}
render() {
return (
<div>I am header</div>
)
}
}
Main.js
import React, { Component } from 'react'
import { Route } from 'react-router-dom'
import Welcome from './Welcome'
import Feature1 from './Feature1'
import Feature2 from './Feature2'
export default class Main extends Component {
render() {
return (
<div>
<Route exact path="/" component={Welcome} />
<Route path="/feature1" component={Feature1} />
<Route path="/feature2" component={Feature2} />
</div>
)
}
}
welcome.js
import React, { Component } from 'react';
export default class Welcome extends Component {
render() {
return (
<div>Welcome!</div>
)
}
}
Feature1.js
import React, { Component } from 'react';
export default class Feature1 extends Component {
render() {
return (
<div>I am Feature1</div>
)
}
}
Feature2.js
import React, { Component } from 'react';
export default class Feature2 extends Component {
render() {
return (
<div>I am Feature2</div>
)
}
}
Welcome, Feature1 and Feature2 are in different routes where as Header is common in all the routes. Say I have a user and I want to show the username on the header. I will make an API call to get the username in componentDidMount() life-cycle hook of header.
Now if I change the route, I don't want the API call to be made again as the username is not going to change. And I thought that is how this was going to behave. As Header component is same in all the routes, I thought Header won't re-mount when I change the route. But that is not what is happening. It is remounting and making the API call again. How can I make sure that the API call is made only once?
I think in this case considering your Header is aware of what User is logged, i.e. App.js state passed down as props, you could use shouldComponentUpdate():
shouldComponentUpdate(nextProps, nextState) {
// see if user changed
if(nextProps.user !== nextState.user){
return true;
}
// returning false will prevent re-rendering
return false;
}
I hope this is somehow useful.
Have a good day!
change to this in index.js:-
<BrowserRouter>
<App />
</BrowserRouter>
It seems you messed up the routing then, because in your router you have only one route registered, which seems to trigger on any child route change. Also, routes should be wrapped in a Switch component.
Check out this structure
/** index.js */
import React from 'react'
import { render } from 'react-dom'
import App from './App';
render(<App />, document.getElementById('root'));
/** App.jsx */
import React from 'react'
import Header from './Header'
import Main from './Main'
import { BrowserRouter, Route, Switch } from 'react-router-dom'
const App = () => (
<div>
<Header />
<BrowserRouter>
<Switch>
<Route exact path="/" component={Homepage} />
<Route exact path="/f1" component={Feature1} />
<Route exact path="/f2" component={Feature2} />
<Route component={NotFound} />
</Switch>
</BrowserRouter>
</div>
)
export default App

this.props.children isnt working with react-router

i am trying to make a navigaton on my website by react-router and typescript. but its not working and instead of Home page i get an empty page
Thats my app.tsx file
// app.tsx
import * as React from 'react';
import '../App.css';
class App extends React.Component<any,any> {
public render() {
return (
<div>
{this.props.children}
</div>
);
}
}
export default App;
index.tsx
// index.tsx
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import './index.css';
import registerServiceWorker from './registerServiceWorker';
import {AppRouter} from './router';
ReactDOM.render(
<AppRouter/>,
document.getElementById('root') as HTMLElement
);
registerServiceWorker();
router.tsx
import * as React from 'react';
import { Route,Router } from 'react-router';
import App from './components/App';
import HomePage from './components/home/HomePage';
import createHistory from 'history/createBrowserHistory';
const history = createHistory();
export const AppRouter = () => {
return (
<Router history={history}>
<Route path="/" component={App} >
<Route path="/" exact={true} component={HomePage} />
</Route>
</Router>
);
}
i dont really dont know what to say. i cant find any possible info about this. If u know better way to make navigation with typescript, react and redux i am open for ideas. thx
In the App component, you are doing {this.props.children}. So you should not pass that component to any route.
You need to add all the routes as a child of that component through which you will get the children in your props.
Also, for switching between routes, you should bind all the routes in the 'Switch' imported from react-router.
So, your router.tsx file should look like:
import * as React from 'react';
import { Route, Router, Switch } from 'react-router';
import App from './components/App';
import OtherComponent from './components/OtherComponent';
import HomePage from './components/home/HomePage';
import createHistory from 'history/createBrowserHistory';
const history = createHistory();
export const AppRouter = () => {
return (
<App>
<Router history={history}>
<Switch>
<Route exact={true} component={HomePage} />
<Route path="/other" component={OtherComponent} />
</Switch>
</Router>
</App>
);
}
By this, you will get the 'HomePage' component at route '/' and OtherComponent at route '/other'.

Categories