简体   繁体   中英

React router Redirect inside a stateless functional component

I am new to react and developing an application which allows user to navigate across pages.

I created a TypeScript Project with following

App.tsx

import React from 'react';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import Login from './login';
import Welcome from "./welcome";
import About from './about';

const RedirectRoute = (props) => {
    // if (!authenticated) {

    // }
    return <Route {...props} />
}

const App: React.FC = () => {

    return (
        <BrowserRouter>
            <div>
                <Switch>
                    <RedirectRoute path="/" component={Welcome} exact/>
                    <RedirectRoute path="/login" component={Login} exact/>
                    <RedirectRoute path="/about" component={About} exact/>
                </Switch>
            </div>
        </BrowserRouter>
    );
};

export default App;

welcome.tsx

import React from 'react';
import {Redirect} from 'react-router-dom';
import {Button} from 'antd';
import Login from './login';
import About from './about';

const Welcome: React.FC = () => {
    const redir = (page: string) => {
        console.log('Page:', page);
        if (page === 'login'){
          // <Redirect to="/login"/>    
        } else if(page === 'about') {
            //<Redirect to="/about"/>
        } 
    }

    return (
         <div style={{textAlign: 'center'}}>
            <div style={{display:'inline-block'}}>

                    <Button
                        key="login"
                        type="primary"
                        onClick={() => redir('login')}
                    >Login Page</Button>

                    <Button
                        key="about"
                        type="primary"
                        style={{marginTop:'20px'}}
                        onClick={() => redir('about')}
                    >Navigation Bar</Button>

            </div>
        </div>
    );
}

export default Welcome;

about.tsx

import React from "react";

const About: React.FC = () => {
  return <div>About Page</div>;
};

export default About;

login

import React from 'react';

const Login: React.FC = () => {
  return (
    <div>Login Page</div>
  );
}

export default Login;

Based on routing configurations in App.tsx pages loading fine (localhost:3000/about or localhost:3000/login and localhost:3000/)

But the problem occurs when I tries to redirect to a page when clicking a button(In my real scenario, I have to navigate to welcome page once login is successful)..

Please clarify on following questions if possible since I am confused: 1. Routing works fine when landing in a page, how to manage it when I want to redirect to a page via code and url should reflect. 2. What is the best way to keep these kinda routing and will it support history when user clicks on back button of browser?

Thank you.

You probably need history

import { createHashHistory } from 'history'

export const history = createHashHistory({
    hashType: 'hashbang'
})

Later importing in inside file:

import { history } from '../helpers'

Put this line of code inside function responsible for authorization / authentication - after subbmiting - this line push user to the path is needed.

history.push('/login')

To navigate via a router on click, you should pass properties to component used in . To do that, replace const Welcome: React.FC = () => { with const Welcome: React.FC = (props) => {

and in redir method instead

 if (page === 'login'){
      // <Redirect to="/login"/>    
    } else if(page === 'about') {
        //<Redirect to="/about"/>
    } 

use

 if (page === 'login'){
    this.props.history.push("/login");
 } else if(page === 'about') {
    this.props.history.push("/about");
 } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM