I am trying to use the 1.0.0-rc1 react-router and history 2.0.0-rc1 to navigate manually through the website after pressing the button. Unfortunately, after pressing the button I get:
Cannot read property 'pushState' of undefined
My router code:
import React from 'react';
import { Router, Route, Link, browserHistory } from 'react-router'
import AppContainer from './components/AppContainer.jsx';
import MyTab from './components/test/MyTab.jsx';
import MainTab from './components/test/MainTab.jsx';
var routes = (
<Route component={AppContainer} >
<Route name="maintab" path="/" component={MainTab} />
<Route name="mytab" path="/mytab" component={MyTab} />
</Route>
);
React.render(<Router history={browserHistory}>{routes}</Router>, document.getElementById('main'));
The navigation button is on MyTab and it attemps to navigate to MainTab:
import React from 'react';
import 'datejs';
import History from "history";
export default React.createClass({
mixins: [ History ],
onChange(state) {
this.setState(state);
},
handleClick() {
this.history.pushState(null, `/`)
},
render() {
return (
<div className='container-fluid' >
<button type="button" onClick={this.handleClick.bind(this)}>TEST</button>
</div>
);
}
});
When I use history with this.props.history everything works fine. What is the problem with this code?
EDIT.
After adding the following:
const history = createBrowserHistory();
React.render(<Router history={history}>{routes}</Router>, document.getElementById('main'));
I try to access my app. Before (without history={history}), I just accessed localhost:8080/testapp and everything worked fine - my static resources are generated into dist/testapp directory. Now under this URL I get:
Location "/testapp/" did not match any resources
I tried to use the useBasename function in a following way:
import { useBasename } from 'history'
const history = useBasename(createBrowserHistory)({
basename: '/testapp'
});
React.render(<Router history={history}>{routes}</Router>, document.getElementById('main'));
and the application is back, but again I get the error
Cannot read property 'pushState' of undefined
in the call:
handleClick() {
this.history.pushState(null, `/mytab`)
},
I thougt it may be because of my connect task in gulp, so I have added history-api-fallback to configuration:
settings: {
root: './dist/',
host: 'localhost',
port: 8080,
livereload: {
port: 35929
},
middleware: function(connect, opt){
return [historyApiFallback({})];
}
}
But after adding middleware all I get after accessing a website is:
Cannot GET /
As of "react-router": "^4.1.1", you may try the following:
Use 'this.props.history.push('/new-route')'. Here's a detailed example
1: Index.js
import { BrowserRouter, Route, Switch } from 'react-router-dom';
//more imports here
ReactDOM.render(
<div>
<BrowserRouter>
<Switch>
<Route path='/login' component={LoginScreen} />
<Route path='/' component={WelcomeScreen} />
</Switch>
</BrowserRouter>
</div>, document.querySelector('.container'));
Above, we have used BrowserRouter, Route and Switch from 'react-router-dom'.
So whenever you add a component in the React Router 'Route', that is,
<Route path='/login' component={LoginScreen} />
..then 'React Router' will add a new property named 'history' to this component (LoginScreen, in this case). You can use this history prop to programatically navigate to other rountes.
So now in the LoginScreen component you can navigate like this:
2: LoginScreen:
return (
<div>
<h1> Login </h1>
<form onSubmit={this.formSubmit.bind(this)} >
//your form here
</form>
</div>
);
formSubmit(values) {
// some form handling action
this.props.history.push('/'); //navigating to Welcome Screen
}
Because everything changes like hell in react world here's a version which worked for me at December 2016:
import React from 'react'
import { Router, ReactRouter, Route, IndexRoute, browserHistory } from 'react-router';
var Main = require('../components/Main');
var Home = require('../components/Home');
var Dialogs = require('../components/Dialogs');
var routes = (
<Router history={browserHistory}>
<Route path='/' component={Main}>
<IndexRoute component={Home} />
<Route path='/dialogs' component={Dialogs} />
</Route>
</Router>
);
module.exports = routes
To create browser history you now need to create it from the History package much like you've tried.
import createBrowserHistory from 'history/lib/createBrowserHistory';
and then pass it to the Router like so
<Router history={createBrowserHistory()}>
<Route />
</Router>
The docs explain this perfectly
Related
Inside App.js:
import React, { useState } from 'react';
import './App.css';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import Dashboard from './components/Dashboard/Dashboard';
import Preferences from './components/Preferences/Preferences';
import Login from './components/Login/Login';
function App() {
const [token, setToken] = useState();
if(!token) {
return <Login setToken={setToken} />
}
return (
<div className="wrapper">
<h1>Application</h1>
<BrowserRouter>
<Routes>
/*<Route path="/dashboard">*/
<Route path="/dashboard" element={<Dashboard/>} /></Route>
/*<Route path="/preferences">*/
<Route path="/preferences" element={<Preferences/>} /></Route>
</Routes>
</BrowserRouter>
</div>
);
}
export default App;`
Inside Dashboard.js (../src/components/Dashboard/Dashboard.js):
import React from 'react';
export default function Dashboard() {
return(
<h2>Dashboard</h2>
);
}
Url: http://localhost:3000/dashboard
I want to see the Dashboard content along with the App page content (Application and Dashboard headers) when I load the browser. But when I load the browser, it only displays the App page content and getting the same error:
"Matched leaf route at location "/dashboard" does not have an element. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page."
You are using Routes instead of Router. Replace it on your line 3 and in the return().
Source: React-router https://v5.reactrouter.com/web/api/Route
//...
import { BrowserRouter, Route, Router } from 'react-router-dom';
//...
return ( ...
<Router>
/*<Route path="/dashboard">*/
<Route path="/dashboard" element={<Dashboard/>} />
/*<Route path="/preferences">*/
<Route path="/preferences" element={<Preferences/>} />
</Router>
...)
export default App;
Please specify which version of React router you are using, since a lot of the functionality has changed, is it 6.4 or is still 5 ?
Either way, please remove the comments of the routes, I don't think they help at all.
if you have chosen BrowserRouter from the 6.4 version then it should be used like this
import { BrowserRouter, Route } from 'react-router-dom';
return (
<BrowserRouter>
<Route path="/" element={<RootComp />} >
<Route path="dashboard" element={<Dashboard/>} />
<Route path="preferences" element={<Preferences/>} />
</Route>
</BrowserRouter>
)
export default App;
Where <RootComp /> should have an <Outlet /> as children
import { Outlet } from 'react-router-dom';
const RootComp = () => {
return <div><Outlet /></div>
}
export default RootComp;
Again, this is for the latest React Router component, however, I would advise using createBrowserRouter() rather than the old component-based trees, this way you can programatically create and manage the routes in an Object.
So my div is not showing up on the localhost site from my login.js file. Am I doing something wrong with the routes or something? I don't know why nothing it is not being shown.
login.js file:
import React from 'react';
const Login = () => {
return <div>Login</div>;
};
export default Login;
Here is my app.js file:
import React, { Fragment } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Navbar from './components/layout/Navbar';
import Landing from './components/layout/Landing';
import Register from './components/auth/Register';
import Login from './components/auth/Login';
import './App.css';
const App = () => (
<Router>
<Fragment>
<Navbar />
<Routes>
<Route exact path='/' element={<Landing/>} />
</Routes>
<section className="container">
<Routes>
<Route exact path='/Register' element={<Register/>} />
<Route exact path='/Login' element={<Login/>} />
</Routes>
</section>
</Fragment>
</Router>
);
export default App;
Please Help!
It's should work.
I test it and It's working! I don't get any problem.
You can test by do these:
Remove 'exact' from each route. In version of router 6 don't need to write 'exact'.
Write route path in lowercase. // => "/login"
And check your Login component's path properly.
Best of Luck. Happy Coding!
I am trying to redirect a user to a new page if a login is successful in my React app. The redirect is called from the auth service which is not a component. To access the history object outside of my component I followed this example in the React Router FAQ. However, when I call history.push('/pageafterlogin'), the page is not changed and I remain on the login page (based on my Switch I would expect to end up on the 404 page). The URL in the address bar does get changed to /pageafterlogin but the page is not changed from the login page. No errors appear in the console or anything else to indicate my code does not work.
How can I make history.push() also change the page the user is on?
// /src/history.js
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
// /src/App.js
...
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import history from './history';
function App() {
return (
<Router history={history}>
<Switch>
<Route path="/" exact component={HomePage} />
<Route path="/login" exact render={() => <FormWrapper><LoginForm /></FormWrapper>} />
<Route render={() => <h1>404: not found</h1>} />
</Switch>
</Router>
);
}
export default App;
// src/services/auth.service.js
import axios from 'axios';
import history from '../history';
const API_URL = '...';
class AuthService {
login(username, password) {
return axios.post(API_URL + 'login', {
username,
password
}).then(res => {
if (res.status === 200) {
localStorage.setItem('user', JSON.stringify(res.data));
history.push('/pageafterlogin');
}
});
}
}
Instead of using BrowserRouter, use Router from react-router-dom
You could see the example here
import { Router, Route, Switch, useHistory, create } from 'react-router-dom';
import { createBrowserHistory } from 'history';
import React from 'react';
const history = createBrowserHistory();
export default function App() {
return (
<Router history={history}>
<Switch>
<Route path="/" exact component={() => <h1>HomePage</h1>} />
<Route path="/login" exact component={Login} />
<Route render={() => <h1>404: not found</h1>} />
</Switch>
</Router>
);
}
function Login() {
React.useEffect(() => {
history.push('/pageafterlogin')
}, [])
return <h1>Login page</h1>
}
If you are looking for a solution to this in 2022 and are using React V18+,
the solution is that React v18 does not work well with react-router-dom v5.
I have not tried with react-router-dom v6 yet, but downgrading to React V17 solved the issue for me.
I removed StrictMode and it solved the problem
import { Router } from 'react-router-dom';
import { createBrowserHistory } from 'history';
import React from 'react';
const history = createBrowserHistory();
export default function MyApp() {
return (
<Router history={history}></Router>
);
}
I had the same problem when I hadn't specified the vesion of 'history'. You need to use a 4.x version with Router 5.x. For example, I use React v18, history v4.7.2 and react-router-dom v5.3.3 and it works fine.
Try
npm i history#4.7.2
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.
I have 2 routes, / and /about and i've tested with several more. All routes only render the home component which is /.
When I try a route that doesn't exist it recognises that fine and displays the warning
Warning: No route matches path "/example". Make sure you have <Route path="/example"> somewhere in your routes
App.js
import React from 'react';
import Router from 'react-router';
import { DefaultRoute, Link, Route, RouteHandler } from 'react-router';
import {Home, About} from './components/Main';
let routes = (
<Route name="home" path="/" handler={Home} >
<Route name="about" handler={About} />
</Route>
);
Router.run(routes, function (Handler) {
React.render(<Handler/>, document.body);
});
./components/Main
import React from 'react';
var Home = React.createClass({
render() {
return <div> this is the main component </div>
}
});
var About = React.createClass({
render(){
return <div>This is the about</div>
}
});
export default {
Home,About
};
I've tried adding an explicit path to about to no avail.
<Route name="about" path="/about" handler={About} />
I've stumbled upon this stackoverflow Q but found no salvation in its answer.
Can anyone shed some light on what might be the problem?
Using ES6 and the newest react-router would look like this:
import React from 'react';
import {
Router,
Route,
IndexRoute,
}
from 'react-router';
const routes = (
<Router>
<Route component={Home} path="/">
<IndexRoute component={About}/>
</Route>
</Router>
);
const Home = React.createClass({
render() {
return (
<div> this is the main component
{this.props.children}
</div>
);
}
});
//Remember to have your about component either imported or
//defined somewhere
React.render(routes, document.body);
On a side note, if you want to match unfound route to a specific view, use this:
<Route component={NotFound} path="*"></Route>
Notice the path is set to *
Also write your own NotFound component.
Mine looks like this:
const NotFound = React.createClass({
render(){
let _location = window.location.href;
return(
<div className="notfound-card">
<div className="content">
<a className="header">404 Invalid URL</a >
</div>
<hr></hr>
<div className="description">
<p>
You have reached:
</p>
<p className="location">
{_location}
</p>
</div>
</div>
);
}
});
Since you've nested About under Home you need to render a <RouteHandler /> component within your Home component in order for React Router to be able to display your route components.
import {RouteHandler} from 'react-router';
var Home = React.createClass({
render() {
return (<div> this is the main component
<RouteHandler />
</div>);
}
});