Champa
Champa

Reputation: 615

How to redirect using react-router-dom

import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import {createStore, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import Reducer from './Reducer/';
import {HashRouter as Router, Route, Redirect} from 'react-router-dom';

import Login from './Components/login.jsx';
import User from './Components/User.jsx';








const store = createStore(Reducer, applyMiddleware(thunk));


 

ReactDOM.render(
    
    <Provider store={store}>
        <Router>
            <div>             
                <Route path='/login' component={Login}/>
                <Route path='/user' component={User}/>
            </div>
        </Router>
        
    </Provider>
    

    ,document.getElementById('root')); 

When the user hits the '/' url i want them to be in the login component, but if i do:

<Route path='/' component={Login}/>

The login component always shows up on every different route. My question is. On the landing page "/" how can i make it so it is the login component, but i dont want it to be there if i go to the user component

Upvotes: 1

Views: 455

Answers (2)

Steven Scaffidi
Steven Scaffidi

Reputation: 2307

You should use exact in your route:

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

In addition, you should consider using Switch component to wrap your routes. This will render exactly one route. By design, React Router renders all routes that match. Read about Switch here: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Switch.md

Upvotes: 1

J Livengood
J Livengood

Reputation: 2738

You could do <Route path='/' component={Login} exact /> to specify only rendering that component when its exactly / and nothing more.

Upvotes: 2

Related Questions