dir.by  
  Search  
Programming, development, testing
React
Create a web application "Login form and send a post request" with React | Visual Studio Code
  Looked at 591 times    
 Create a web application "Login form and send a post request" with React | Visual Studio Code 
last updated: 19 February 2025
Download the example
my_react_login_form,zip ...
Size: 3 kilobytes
File structure:
D:/my_react_login_form
        .babelrc                          configuration file for Babel
        index.html
        package.json                  configuration file for Node.js (contains package names)
        style.css                         styles for html
        webpack.config.js         configuration file for Webpack (How to merge JS files into one)
        .vscode
                launch.json            configuration file for Visual Studio Code (path to the executable file)
        src
                main.js
        build
                transformed.js       After running Webpack, this file will be generated
Note! You must have Node.js installed. If you don't have it, then need to download and install Node.js ...

Note! You must have Visual Studio Code installed. If you don't have it, then need to download and install Visual Studio Code ...
 
Step 1. Creating a new React app
Step 2. Let's add the code to the file main.js
The render method is called by the React library.

When we click on the Login button, my method onLoginSubmit will be called.
My method onLoginSubmit sends an http request to the site https://dir.by/developer/myapi/login.php (to do this, I call the axios.post command).
Currently, when writing React applications, Component is not used after 2020.
Our React program is function.
function returns html this is the appearance of the application.
Using Component is a bad rule.
Using function is a good rule.
File main.js
  JavaScript  
var React = require("react");
var ReactDOM = require("react-dom");
import { Component } from "react";
import axios from 'axios';

class MyApp extends Component {

     onLoginSubmit(e) {
          e.preventDefault();

          let urlLogin = "https://dir.by/developer/myapi/login.php";

          let sendObject =
               { 'login': e.target.login.value, 'password': e.target.password.value };

          let axiosConfig =
               { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } };

          axios.post(urlLogin, sendObject, axiosConfig)
               .then(function (response) {
                    alert(JSON.stringify(response.data))
               })
               .catch(function (error) {
                    alert("Error ! " + error)
               });
     }

     render() {
          return (
               <div class="container1">
                    <div class="container2">
                         <div class="form1">
                              <h2> Welcome </h2>
                              <form onSubmit={ this.onLoginSubmit }>
                                   <div>
                                        <input type="text" name="login" />
                                   </div>
                                   <div className="vert1">
                                        <input type="text" name="password" />
                                   </div>
                                   <div className="vert1">
                                        <button>Login</button>
                                   </div>
                              </form>
                         </div>
                    </div>
               </div>
          );
     }
}

ReactDOM.render(
     <MyApp ></MyApp>,
     document.getElementById('my_container'));
File main.js
  JavaScript  
var React = require("react");
var ReactDOM = require("react-dom");
import axios from 'axios';

 
function MyApp() {

     const onLoginSubmit = (e) => {
          e.preventDefault();

          let urlLogin = "https://dir.by/developer/myapi/login.php";

          let sendObject =
               { 'login': e.target.login.value, 'password': e.target.password.value };

          let axiosConfig =
               { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } };

          axios.post(urlLogin, sendObject, axiosConfig)
          .then(function (response) {
               alert(JSON.stringify(response.data))
          })
          .catch(function (error) {
               alert("Error ! " + error)
          });
     }

 
     return (
     <div class="container1">
          <div class="container2">
               <div class="form1">
                    <h2> Welcome </h2>
                    <form onSubmit= { onLoginSubmit } >
                         <div>
                              <input type="text" name="login" />
                         </div>
                         <div className="vert1">
                              <input type="text" name="password" />
                         </div>
                         <div className="vert1">
                              <button>Login</button>
                         </div>
                    </form>
               </div>
          </div>
     </div>
     );
 
}

ReactDOM.render(
     <MyApp ></MyApp>,
     document.getElementById('my_container'));
Step 3. Let's add the code to the file style.css
  CSS     File style.css
.vert1 {
     padding-top:20px;
}

.container1 {
     display: flex;
     justify-content: center;
     align-items: center;
     height: 100%;
}

.container2 {
     display: flex;
     flex-direction: column;
     justify-content: center;
     align-items: center;
     background-color: #cccccc;
     height: 50%;
     width: 50%;
}
Step 4. The server receives the post request. The server creates a response here in the login.php file
  PHP     File login.php
<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

header('Content-Type: application/json');

$response = array();
$response['success'] = false;

if ($_REQUEST['login']=='evgen' && $_REQUEST['password']=='12345')
{
     $response['success'] = true;
     $response['token'] = "123123dasa213ws212";
}

echo json_encode($response);

?>
How do I run the sample locally on my computer?
Step 1.
Open
Visual Studio Code
and select React project
In Visual Studio Code click on the menu FileOpen Folder
and select the folder D:/my_react_login_form
Step 2.
Installing libraries
In Visual Studio Code click on the menu TerminalNew Terminal
Perform:
npm install


See the picture:


Explanation:
There are no js libraries in this zip archive.
The names and versions of the js libraries are written in the package.json file.
When executed on the npm install command line, libraries with the name and versions from package.json will be downloaded from the Internet and installed in the node_modules folder.
Step 3.
Compile the React project
Perform:
npm run MyBuild


See the picture:

Explanation:
The npm run MyBuild command runs the script MyBuild.
The script MyBuild is defined in the package.json file.
File D:/my_react_login_form/package.json:
{
...
    "scripts": {
        "MyBuild": "webpack"
    }
...
}

The script MyBuild will run Webpack.
Webpack take the file evgen.js and take the files React and pack all the code from these files into one file transformed.js
Step 4.
Run the React project
In Visual Studio Code click on the menu RunRun Without Debugging

See the picture:

In the Google Chrome browser, a new page will be opened with the address: file:///D:/my_react_login_form/index.html
 
See the picture:


Explanation:
index.html
starts because the .vscode/launch.json configuration file contains the following parameter:
"url": "${workspaceFolder}/index.html"

Setup file .vscode/launch.json
{
"version": "0.2.0",
"configurations": [
     {
          "type": "chrome",
          "request": "launch",
          "name": "Launch Chrome",
          "url": "${workspaceFolder}/index.html"
     }
]}
Note!
If you have changed the src/main.js file, then you need to:
 
Go to step 3 (compile the React project) ...
 
Go to step 4 (run the React project) ...
 
← Previous topic
Why don't they use class Component, but you have to use a regular function in React app?
 
Next topic →
Sites to explore React
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

  Объявления  
  Объявления  
 
Новое приложение React
Вариант 1
Создаем новое web приложение с React в текстовом редакторе. Библиотеку React не скачиваем, библиотеку React берем из CDN (ссылаемся на библиотеку React)
Вариант 2 (для меня лучший)
Creating new web application with React using Visual Studio Code. Use: Node.js + Webpack (collect all js files, libraries into one js file) + Babel (extended js functionality with jsx and classes) + React (write our component)
Описание React
Why don't they use class Component, but you have to use a regular function in React app?
Examples
Create a web application "Login form and send a post request" with React | Visual Studio Code
WWW sites to explore React
Sites to explore React

  Ваши вопросы присылайте по почте: info@dir.by  
Яндекс.Метрика