Jur Dekker
Jur Dekker

Reputation: 151

React Route URL

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?

Upvotes: 1

Views: 123

Answers (1)

Gavin Thomas
Gavin Thomas

Reputation: 1867

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.

Upvotes: 1

Related Questions