React router render component on same page

All we need is an easy explanation of the problem, so here it is.

im using react router on my project, when i hit the login button, it renders the content of App component, but displays them on the same page. i want to display on new page when i hit login, help me

import React, { Component } from 'react';
import * as service from '../services/service';
import '../App.css'
import '../index.css'
import App from'../App'
import { Link, Redirect, Router, Route, browserHistory,IndexRoute } from 'react-router';
// import createHistory from 'history/createBrowserHistory'

class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      messages: []
    }
  }
  onSubmit() {
    browserHistory.push('/world');
    }
  render() {
    const { messages } = this.state;
    return (
      <div className="App">
        <header>
          <h2> Doctor Login Page </h2>
        </header>
        <form>

        <Router history={browserHistory}>
        <Route path="/world" component={App}/>
      </Router>
          <br /><br /><br />
          Username: <input name='email' placeholder='Email' /><br /><br />
          Password: <input name='password' placeholder='Password' type='password' />
          <br /><br />
          <button onClick={() => this.onSubmit()}>Login</button>
        </form>
      </div>
    );
  }
}

export default Login;

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

It looks like you want to tackle this in either two ways

1) Use the ‘exact path’ property from the react-router library

<Route exact path="/world" component={App}/>

2) remove the code below the route and put that into a component itself and declare its own route as your code above has the main router running as well as leaving static JSX below the routers.

<Route exact path="/" component={Login}/>
<Route exact path="/world" component={App}/>

Method 2

Be sure to put the most specific route at the top. React route will scan each route once find a match it will redirect to that route in case you didn’t use the ‘exact’ keyword.

example:

<Route path="/world" component={App}/>
<Route path="/" component={Login}/>

I had this issue before and to reorder of the routes was the solution in case of anyone face this in the future.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply