1

I'm new with React. I'm using react-router-dom.

import React from 'react';
import { Router, Route, Switch, Link } from 'react-router-dom';
import Home from './components/home';
import Login from './components/login';

class App extends React.Component {

constructor(props) {
    super(props);
}

render() {
    return (
        <div className="app">
          <Link to='/'>Home</Link>
          <Link to='/login'>Login</Link>
          <Switch>
            <Route exact path='/' component={Home}/>
            <Route path='/login' component={Login}/>
          </Switch>
        </div>
    );
  }
}
export default App;

I'm using this code everything work fine, but when I go to localhost:8080/login directly via de url I get a error Cannot GET /login but it goes well through a link <Link to='/login'>Login</Link>.

how can I fix it?

3
  • 1
    Please check this answer stackoverflow.com/questions/40332753/… Commented Dec 16, 2017 at 14:45
  • @ShubhamKhatri almost, but i found a next problem, how can I remove the # from http://localhost:8080/#/home Commented Dec 17, 2017 at 12:35
  • Instead of using HashRouter, you would use BrowserRouter Commented Dec 17, 2017 at 12:38

1 Answer 1

1

So this is often a tricky thing I deal with in regards to navigating with react.

By navigating directly to /login your React App hasn't actually rendered the highest parent or root and thus there really isn't a login component to find and render. Here's what I do when working with logins and home

<Route exact path="/" component={() => this.props.auth ? <DashboardContainer/> : <Redirect to="/" />}/>

This says if there isn't any auth (or local storage, or cookies, or whatever you're using to log them in) redirect back home or to / so they can click /login.

Basically you need your highest level component to mount virtually before you can do anything else. You can also make /login your landing page, so in this case merge / and /login. But the above example is modularized and dynamic.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.