React uses routing to redirect to the login interface

React uses routing to redirect to the login interface

In the previous article, after configuring the webpack and react environment, we started to write the login interface and the subsequent jump to the homepage function.

1. First, take a look at the overall directory structure.

Because many times when you are looking at examples written by others, unexpected problems may occur due to unfamiliarity with the directory structure.

Overall directory structure

2. General process:

1) webpack configuration entry file src/index.js
2) After running index.html, first load the entry file src/index.js
3) Load the routing table src/router/index.js
4) According to the configuration in the routing table, the login interface src/login.js will be loaded first
5) When you successfully log in to the login interface, jump to src/components/myView.js
6) Clicking the left menu in the myView file will display the specified pages (all configured in the routing table)

3. Write HTML files.

Among them, 1) the id myContent is used to place the components we wrote.
2) The file loaded in the script is the js file packaged by webpack.

<body>
 <div id="myContent"></div>
 <script src="./dist/bundle.js"></script>
</body>

4. The login interface is written in login.js

1) Introduce necessary modules: antd (Ant Design) is a component library, and all the components used in our project come from it. (https://ant.design/index-cn) (If antd.css is not introduced, the interface will not display the style)

import React from 'react'
import {Form,Input,Icon,Button} from 'antd'
// import {render} from 'react-dom'
// import axios from 'axios'

import '../node_modules/antd/dist/antd.css' //If you don't import this file, the antd style will not be displayed import './style/login.css';

2) Create a login form component. In addition to the basic Form, Input, and Button components, the main function for implementing the jump function is history.push('/View'); (where history = this.props.history;). The path in the push function is the path configured in the routing table ( ), and the two must correspond.

class LoginFrom extends React.Component{
 constructor(){
 super()
 }

 handleSubmit = (e) => {
 //Before submitting, check whether the input field has errors e.preventDefault();
 
 **let history = this.props.history;**
 this.props.form.validateFields((errors,values)=>{
  if (!errors) {
  console.log('Received values ​​of form: ', values);
  **history.push('/View');**
  }
 })
 }

 render(){
 //The component wrapped by Form.create will have its own this.props.form property, which provides a series of APIs, including the following 4 //getFieldDecorator is used for two-way binding with the form //isFieldTouched determines whether an input control has experienced the value collection timing of getFieldDecorator options.trigger (the timing of collecting the value of the child node, the default is onChange)
 //getFieldError gets the Error of an input control
 //Get the Error of a group of input controls. If no parameters are passed, the Error of all components will be obtained.
 const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched } = this.props.form;
 const userNameError = isFieldTouched('userName') && getFieldError('userName');
 const passWordError = isFieldTouched('password') && getFieldError('password');
 return (
  <div className="login">
  <div className="login-form">
   <div className="login-logo">
   <div className="login-name">MSPA</div>
   </div>
   <Form onSubmit={this.handleSubmit}>
   {/* Put a child decorated by getFieldDecorator in a FromItem */}
   <Form.Item
    validateStatus={userNameError ? 'error' : ''} //validateStatus is the validation status. If not set, it will be automatically generated according to the validation rules. Optional: 'success' 'warning' 'error' 'validating'
   >
   {
    getFieldDecorator('userName',{
    rules:[{required:true,message:"Please input your username!"}]
    })(
    <Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }}/>}
     placeholder="Username"
    />
    )
   }
   </Form.Item>
   <Form.Item
    validateStatus={passWordError ? "error" : ''}
   >
   {
    getFieldDecorator('passWord',{
    rules:[{required:true,message:"Please input your Password!"}]
    })(
    <Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }}/>}
     placeholder="Password"
    />
    )
   }
   </Form.Item>
   <Form.Item>
    <Button
    type="primary"
    htmlType="submit"
    disabled={hasErrors(getFieldsError)}
    >Login</Button>
   </Form.Item>
   </Form>
  </div>
  </div>
 )
 }
}
let LoginForm = Form.create()(LoginForm);
export default LoginForm;

3. In the second step, we have written the static page, and the next step is to configure the routing table**. **We configured the routing information in index.js under the router folder. react-router Chinese documentation (https://react-guide.github.io/react-router-cn/), where a brief introduction to history can be referenced (https://www.jb51.net/article/208929.htm), which is relatively easy to understand quickly.


The code is as follows: the modules introduced in the first three lines are basic modules, and the modules imported later are pre-written components: the home page displays the login interface, and jumps to the myView interface after successful login. myPicture and myDocument are the components displayed after clicking on the myView interface. (Nested Routes)

import React from 'react'
import {HashRouter as Router , Route , Switch} from 'react-router-dom'
import { createBrowserHistory } from "history";

import MyView from '../components/myView.js'
import LoginModule from '../login.js'
import MyPicture from '../components/myPicture'
import MyDocument from '../components/myDocument.js'

export default class MyRoute extends React.Component{
 render(){
 return(
  <Router history={createBrowserHistory()}>
  <Switch>
   <Route exact path="/" component={LoginModule}/>
   <MyView path='/View' component={MyDocument}>
   <Route path="/View/abc" component={MyDocument} />
   <Route path="/View/myPicture" component={MyPicture} /> 
   </MyView> 
  </Switch>
  </Router>
 )
 } 
}

4. Next, we write the following code in the index.js (entry file of the program) file in the src folder.

import MyRoute from './router/index.js'
import {render} from 'react-dom'
import React from 'react'
render(
 <MyRoute />, 
 document.getElementById('myContent')
);

5. The program test results are as follows:

1) Login interface (login.js):


2) Enter the username and password and click the login page (myView.js):

insert image description here

This is the end of this article about using React to use routing to redirect to the login interface. For more information about using React routing to redirect to the login page, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Implementation steps for setting up the React+Ant Design development environment
  • How to build a React project with Vite
  • React example of how to get the value of the input box
  • React implements the sample code of Radio component
  • Let's talk about my understanding and application of React Context
  • React hooks introductory tutorial
  • Detailed process of creating a VR panoramic project using React and Threejs
  • A brief talk about React Router's history
  • How to simplify Redux with Redux Toolkit

<<:  A simple way to change the password in MySQL 5.7

>>:  A brief discussion on why daemon off is used when running nginx in docker

Recommend

Docker connects to the host Mysql operation

Today, the company project needs to configure doc...

MySQL 5.7.17 compressed package installation-free configuration process diagram

There are two versions of MySQL database manageme...

Detailed steps for deploying Tomcat server based on IDEA

Table of contents Introduction Step 1 Step 2: Cre...

Json advantages and disadvantages and usage introduction

Table of contents 1. What is JSON 1.1 Array liter...

JavaScript custom plug-in to implement tab switching function

This article shares the specific code of JavaScri...

Docker uses nextcloud to build a private Baidu cloud disk

Suddenly, I needed to build a private service for...

js canvas to realize the Gobang game

This article shares the specific code of the canv...

Solution to the problem of MySQL deleting and inserting data very slowly

When a company developer executes an insert state...

React Native JSI implements sample code for RN and native communication

Table of contents What is JSI What is different a...

MySql learning day03: connection and query details between data tables

Primary Key: Keyword: primary key Features: canno...

How to set up the terminal to run applications after Ubuntu starts

1. Enter start in the menu bar and click startup ...

React High-Order Component HOC Usage Summary

One sentence to introduce HOC What is a higher-or...