Writing

Front-End Web Development with React

GeneralJava scriptForm validationsFront End Web Development with ReactJSXJavaScriptNPMReactReact RouterReact Virtual DOMReact containerSingle Page ApplicationWeb Developmentcontrolled formsformsfront endjavaScript frameworksnode jsnode package manageruncontrolled forms

Hi, I took this course on Front-End Web Development with React by The Hong Kong University of Science and Technology, so this is a gist of that course.

Prerequisites would be HTML, CSS , Bootstrap and basic JS

  1. http://programmerprodigy.code.blog/2020/06/18/web-developmenthtmlcss-basics/
  2. http://programmerprodigy.code.blog/2020/06/24/javascript-basics-for-web-development/

If you get Stuck at any JavaScript concept, please refer this document. I have tried to add most commonly used JavaScript concepts in it along with examples, https://programmerprodigy.code.blog/2020/08/16/key-words-used-in-react-js/

Q. What is a full stack developer?

Learning about both client and server-side code and understand how the full suite of technologies making up a website work.

  1. On the client side, you want to build everything you actually see on a website (e.g., the layout, the positioning of text and images, colors, fonts, buttons, etc.) using, typically, HTML, CSS, and JavaScript.
  2. On the server side, you want to create algorithms and business logic to manipulate data that is received from the client side.

[Image no longer available]

  1. https://www.laurencegellert.com/2012/08/what-is-a-full-stack-developer/
  2. https://www.andyshora.com/full-stack-developers.html

Q. What is Node.js, NPM and Yarn?

Node.js is based on the JavaScript runtime engine that has been built for the Chrome browser. So the Chrome V8 JavaScript engine has been ported from the browser to run on the desktop and support the execution of JavaScript programs on the desktop.

how to install node js

When you install Node on your computer, NPM automatically gets installed. The Node Package Manager is the manager for the node ecosystem that manages all the node modules and packages that have been made publicly available by many different users. https://nodejs.org/en/download/package-manager/

Verify by checking the version of both of them

My version of Node and npm

The official documentations:

  1. https://docs.npmjs.com/
  2. https://nodejs.org/api/
  3. https://www.npmjs.com/products/pro
How to install Yarn

Yarn is another package manager like NPM, but is better suited and faster to work with for React applications. So let us install yarn and use it for building our React applications.To install Yarn, you can find the instructions for your specific platform at https://yarnpkg.com/en/docs/install.

My version of yarn

Q.What is package.json file?

The package.json file serves as the documentation on what all other packages that your project is dependent upon. So, for example, when you set up the lite-server for your project that will be recorded in the package.json file, so that subsequently you can also make use of that package in the future.

It allows you to specify which specific version of a package that your project is dependent on, and also it makes your builds reproducible. Which means that when you share your code with others, then they can also do installation of all the node modules,

If you are starting a new project where you want to initialize the package.json file then simply type npm init at the prompt in the project folder and then that will take you through a set of steps, which will enable you to configure your package.json file.

npm init

How package.json looks like

Q.How we can install a node module using NPM(the node package manager) and Yarn ?

So, we’re going to install this node module called as lite-server. The lite-server will serve up the contents of this folder in a server that it starts up, so that you can view the contents in a browser.

Using npm:

npm install lite-server --save-dev

If you are installing a node module on which your project is directly dependent on, then you would install it by simply saying minus minus save-option.

Using yarn:

yarn add lite-server

For more information on lite-server

Q. How to not add node modules to our git repository?

When you upload the contents of your folder to an online Git repository or when you do a commit of the folder to your Git repository, you don’t want the node modules folder or all the subfolders under it to be included in the commit.

So to do that, we will set up a file named dot Git ignore. So that’s the name of the file, dot gitignore. To create this dot gitignore file, we will go to our editor.

Q.What are JavaScript frameworks and libraries? Why do we need them? And what do they help us accomplish that we cannot do with standard Vanilla JavaScript?

The genetic framework defines a standard set of behaviors that you can then customize to implement your specific application. So the framework will call upon their specific functionality that you implement as a web application designer in order to customize the generic functionality that the framework provides. This is where we often hear about the inversion of control.

So this is where we also distinguish between two different approaches to implementing applications, the imperative approach as opposed to the declarative programming approach.

  1. In an imperative approach, the application designer clearly specifies how the work needs to be accomplished or how the application needs to be executed.
  2. In a declarative approach, the application designer simply specifies what needs to be accomplished and leaves it up to the framework to decide how the work is going to be accomplished.

For more information

Q.What is React library?

React as specified on its website says that, it makes it easy to create interactive UIs with simple views for each state within your application. And also React takes care of automatically updating the UI and then rendering any changes to their specific components as required on your page. In a Component based approach, we encapsulate behaviors into small units called Components.

React was first designed by Jordan Walke who was part of the Facebook team. It was first deployed for Facebook’s news feed around 2011. Subsequently in 2013, React was open sourced at this JS conference. React took off as an approach for implementing Web applications from then onwards. React is designed for speed, speed of implementing the application, simplicity, and scalability.

From the React documentation we learn that the create-react-app CLI makes it easy to create an application that already works, right out of the box.

1.To install create-react-app globally, type the following at the prompt:

yarn global add create-react-app

2.This will make the command line tool for creating React applications. To learn more about the various commands that this CLI provides, type at the prompt:

create-react-app --help

3.This should create a new folder named your app within your React folder and create the React application in that folder. Move to the your app folder and type the following at the prompt:

yarn start

Type create-react-app –help and that will print out a set of instructions on how we can use the create react app to create a React application

A few important files to know about:

1. Index.js:

In this React Element, you’re noticing h1 tag here, which seems to remind you of the html h1 tag. What this represents in React, is plain Javascript object. And so in React, all these elements are plain JavaScript objects, that are very cheap to create and so you can create a lot of them for use within your React Application.

So, you can see that you’re importing React from React, and then you’re importing ReactDOM from react-dom, and then you’re importing the CSS file here, and then you’re importing App from.App. .

This ReactDOM, as you see, is imported from react-dom and then you’re calling the render method of ReactDOM and then for that, you are supplying the first parameter as App. So this is a tag here, the App here refers to this App that we are just importing, and so that is a self closing tag that we have enclosed here, and then the second parameter here that says document.getElementById(‘root’). Now from your knowledge of JavaScript, document refers to the HTML document that we have seen and then says getElementById(‘root’) here. And so, you can interpret the statement saying ReacDOM.render. This particular thing, and then attach it to this DOM element in my index.html page.

import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
2.App.js:

Q.What is this component class?

So we are importing this from this React module here. Then component, class from there. And that is what we are using to create this subclass here called app. And then inside this App class, you’ll see that there is a single method here called render here. The render method contains, as you can see React Elements that are grouped together. Innovate to create the view that you saw in the browser a little bit earlier. So, this is returned by this render method of this render function of this class component here. So, this is the typical structure of the React component.

If you scroll down, it says export default App; So, this app is an export from this App.js file. Also, notice that we are importing App.css here before applying it to our application.

import React from 'react';
import {Navbar, NavbarBrand} from 'reactstrap';
import './App.css';

function App() {
  return (
    <div className="App">
      <Navbar dark color="primary">
        <div className="container">
          <NavbarBrand href="/">
            Hridyesh Singh Bisht
          </NavbarBrand>
        </div>
      </Navbar>
      <h2>Hello World</h2>
    </div>
  );
}

export default App;
3.Index.html:

Let me draw your attention to this particular element in there written div id root here. So what you can see here is that in the index.html page, I am rendering that particular DOM element, onto this element in my index.html page. So this is going to be replaced by what is rendered by index.js, and put in there in place of that, and which is nothing but what is included inside this app component, which is nothing but what we just saw here which is being rendered by the app component.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>

Introduction to JSX

You have never seen something like this before where HTML code gets engulfed inside my JavaScript code. And so, this is the special syntax that react to uses when it expresses the various react elements.

JSX is syntactic extensions to JavaScript which enables us to express react elements using it HTML like syntax. So, it is a shorthand notation from JavaScript functions that are called, which evaluate the JavaScript object. So, as we will see, the reason for approaching it this way as opposed to having the HTML separate from the JavaScrip code as done in other frameworks used to avoid the artificial separation of the rendering logic from the other UI logic. Very often, what is rendered in the screen is dependent upon the rest of the UI logic controlling the rendering on the screen.

So again, illustrating this with an example, you might see a react element being defined like this in the code. Now, then you’ll see this, you obviously notice immediately some HTML like syntax in the code, and some specification of attributes for the HTML like elements and so on. But in reality, this actually gets mapped in react into a corresponding JavaScript object here.

[Image no longer available]

Configuring your React Application

Furthermore, the JavaScript part of Bootstrap cannot be directly used together with React. What Reactstrap supplies is Bootstrap components re-implement using React components. And so we can make use of them. Like for example, on the JavaScript-based components and Bootstrap have been re-implemented using React components in Reactstrap.

Configure your React Project to use Reactstrap

1.To configure your project to use reactstrap, type the following at the prompt to install reactstrap, and Bootstrap 4:

yarn add bootstrap
yarn add reactstrap
yarn add react-popper

You can also install the same using npm using the “npm install –save” option if you are using npm instead of yarn.

2.Next, open index.js file in the src folder and add the following line into the imports:

import 'bootstrap/dist/css/bootstrap.min.css';

3.Open App.js in the src folder and update it as follows:

import React from 'react';
import {Navbar, NavbarBrand} from 'reactstrap';
import './App.css';

function App() {
  return (
    <div className="App">
      <Navbar dark color="primary">
        <div className="container">
          <NavbarBrand href="/">
            Hridyesh Singh Bisht
          </NavbarBrand>
        </div>
      </Navbar>
      <h2>Hello World</h2>
    </div>
  );
}

export default App;

For more Information,

  1. https://github.com/facebook/create-react-app
  2. https://reactstrap.github.io/
  3. https://reactjs.org/docs/introducing-jsx.html

React Components :

We can look at a component as a unit that returns a group of React elements that together render it part of the screen. So the components acts as a unit for gathering together a bunch of React elements with a common purpose.

Any component in React, a class component should implement this method called render() which will turn the corresponding view for this component. So, inside this render method, I need to return the view for this component. Also when you create the component, don’t forget to export that component from this file, because we would need to import this component wherever we want to make use of it within our application.

The app component that I’ve just created now becomes available within my app component. Now if I want to make use of the app component inside my component, all I need to do is go down and then simply state the exported variable with a self closing tack and that’s it.

For more information

When you declare the constructor, you would initialize a variable called this dot state which is a JavaScript object which contains all the state for this component. If you need to update the state of a component, you cannot directly go and update the state by changing the property values. Instead, any update to a state of the component has to be done through the use of that Sect State method.

FunctionName(parameter) {
        this.setState({ variable: parameter});
    }

Another way of passing information to a component is through Props. Each component can store its own local information in its state quote and quote. So this information is private and fully controlled within that component. Now is state within a component can easily be passed to its children through the use of props.

Now, the arrow function is used, if you want to pass some information or parameter back to the the event handler. If you don’t have any parameters or data to be passed back to the event handler, then you can simply say this. on. Some Function instead of defining it as the arrow function.

So for example, if several components have a shared state and any change to the state needs to be automatically seen by all these components, then it is better to move the state to one of the ancestors, common ancestor of all these components, and ensure that any state changes will be sent back up to that common ancestor. Any changes to data in one component may need to be reflected to another component, and this is where by lifting the state up it makes it more convenient for you to handle this. When you have an array of items, you could easily lay them out as list in your react components. Lists and the way you handle them is very similar to JavaScript.

For More information

Life cycle of the component:

Each React component as in when it is required will be created by React and then added into the DOM of your entire application. So, every time a React component needs to be included into your applications view, then the component that hosts the specific part of the view will be created and added into the overall React component hierarchy.

The life cycle for the component,

  1. Initially, the component doesn’t exist,
  2. then the component gets created and then once it is created,
  3. then it can be mounted into your React application at an appropriate point in the hierarchy of components,
  4. then it will exist at that point for a period of time and
  5. then subsequently, maybe you no longer require that view, and so at the point, the component can be removed from this hierarchy.

When a component is being updated, there are several lifecycle methods associated with this process. So these lifecycle methods are called when a component is being re-rendered or being updated. Now, this could be caused either because the props that are supplied to the component changed, or the internal state of the component changed.

So, as you realize, a component passes through a life cycle of creation, mounting, and then existing in the hierarchy, then unmounting, and then disappearing at the point.

For more information

Container Components

So, if you view your React application as consisting of these two kinds, then implementing your application or at least thinking of how you implement your application becomes more easier.

  1. Presentational components that are purely responsible for the views,
  2. Container components that make use of the presentational components in order to construct the overall view of your application.

For more information,

  1. Presentational and Container Components
  2. Presentational and Container Components (Redux Perspective)

Q.When to use Functional components or Class based components?

If your component is a very simple component and doesn’t require this much of elaborate implementation, there’s a much simpler way of implementing React Components. This simple way of implementing React Components is called as Functional Components.

Functional Component the easier way of doing this is to simply define a JavaScript function that returns either one react element or a collection of react elements too that defines the view that this component is supposed to render. So, a Functional Component is a lot more simpler way of implementing the component where you don’t need a local state, where you don’t need access to life lifecycle hooks. So, this Functional Components simply receives props as it’s parameter. So, within the props all the attributes that we define, all the component will become available within our component, and we can make use of them when they render the views. But the only restriction is that Functional Components cannot have any local state and cannot have access to the lifecycle hooks

function Home(props) {
    return(
      <div className="container">
        <h4>Home</h4>
      </div>
    );
}

For more information,

  1. React Component Patterns
  2. Functional Stateless Components in React

React Virtual DOM

The Virtual DOM is a React object. The Virtual DOM in React terminology is a lightweight representation of a Browser DOM. Now, since the Virtual DOM is an in-memory object in your React application, the Virtual DOM can be easily manipulated by React whenever it’s required.

So, manipulations are extremely fast compared to manipulating the Browser DOM. When you change anything in the Browser DOM, you need to go and re-render the web page allover again. But the Virtual DOM, since it is maintained in memory by your React application, you can easily make changes to the Virtual DOM.

So, when you have any changes to the state of your components or changes to the props that a component obtains, then that may result in the component being re-rendered. So, this re-rendering is initially done to the Virtual DOM, so any changes are reflected at the Virtual DOM first. And then, after that, we will see how the Browser DOM gets manipulated.

So this Virtual DOM is created completely from scratch every time you call the setState. So, you’ll see that whenever you call setState, you are changing the state with a new React application, which also means that it is possible that some of the props passed into the child components to change, and so the child components may have to be re-rendered.

Every time there are changes to the Virtual DOM and you are at the point of re-rendering the view in the Browser DOM, then to update the DOM, React runs in diffing algorithm. The diffing algorithm identifies the minimum number of components or minimum part of the tree that needs to be updated in order to make the modified version in sync with that Browser DOM.

For example, in a list. You can use the key attribute in the list items in order to indicate which child elements are stable. Indeed, that is the reason when we rendered list, we always supply the key attribute to each list item, and each key attribute was a unique identifier for that particular item in the list. So, when the diffing algorithm works, if it notices that some parts of the list cannot change, they don’t need to be re-rendered. And so, it’ll re-render only those list items that have actually been modified.

React Router

The React Router module, we install it into our React Application and then take the help of the various features provided by the React Router module to enable us to navigate among the views of our application.

yarn add react-router-dom

A React Router is a collection of navigational components. These are React components themselves and these React components enable us to navigate among various views or navigate among various pages. Now, the React Router itself provides larger components than route matching components and a navigation components.

So since we are implementing a web application, we’ll use react-router-dom to implement the react. And this makes available to us a Router component and one of the router components is a BrowserRouter component. So this BrowserRouter component will be applied within one of our components in our application, and this enables the BrowserRouter to provide us with a specialized history object that enables us to navigate among the pages just like the way we navigate among the various pages in a website. If you are using a static file server, then there is a corresponding component called the HashRouter which enables you to do navigations to URLs that contain hashes.

The route matching components include the Route and the Switch. The route component enables us to specify a path property which specifies the current location’s pathname. So, this is the URL part that will be interpreted to represent a particular view. So, each view will be identified by its own URL. And the route components prop, specifies the corresponding view of the application. You could also provide a default by using the redirect components. So, the redirect will specify the default URL to which you’ll be redirected if any of the other parts do not match with any of the routes that you specify within application.

Now, if you have a bunch of routes that you specify, bunch of route components, you group them together using a switch component. So this way, whenever the URLs are navigated to, then this will iterate over all the children to find that particular component or that particular route that matches the URL and then appropriately navigates to that view.

<Switch>
                <Route path='/home' component={HomePage} />
                <Route exact path='/menu' component={() => <Menu dishes={this.state.dishes} />} />
                {/* Pass in parameters in the above statement */}
                <Route path='/menu/:dishId' component={DishWithId} />
                <Route exact path='/contactus' component={Contact} />
                <Route exact path="/aboutus" component={() => <About leaders={this.state.leaders} />} />                  
                <Redirect to="/home" />
</Switch>

But ideally I would want to have the navigation built into my nav bar here and also to activate these links. So that if I click on them, I will be able to navigate to the various views of my application. So how do we do that? We’ll go into the head of component and configure our nav bar to contain the links that will help me to navigate between the various views of the application.

[Image no longer available]

For more information,

  1. React Router Documentation
  2. React Router Dom Documentation
  3. React Router DOM: set-up, essential components, & parameterized routes
  4. Basic intro to React Router v4
  5. A Simple React Router v4 Tutorial
Q.How to pass parameters through the URL, and make use of the parameters in another component in order render the view there.

if you specify a path like that with a parameter starting with a colon, then whatever follows that will be interpreted as a route parameter by React Router.

Now when this happens, this route information, what the route component does, is it passes three pass props to the component which it is rendered. Three props that it passes is called match, location, and history.

<Switch>
        <Route path="/home" component={HomePage} />
        <Route exact path="/menu" component={() => <Menu dishes={this.props.dishes} />} />
         {/* passing parameters in the above route */}
        <Route path="/menu/:dishId" component={DishWithId} />
                        
</Switch>

Q.How the match prop can be used to extract the parameter that is passed in the URL?

This match object enables us to determine a path. So, when you specify various route parameters, these become available through the match object as params, which is a propagated gets associated with the match object. So, when you say match.params, you’ll be able to get access to all the params, as a key value pair here. So, each param is associated with a key value pitch. So, params, said if we specified the path as menu:id, then this id will be used as a key and the value.

const DishWithId = ({match}) => {
      return(
          <DishDetail dish={this.state.dishes.filter((dish) => dish.id === parseInt(match.params.dishId,10))[0]} 
            comments={this.state.comments.filter((comment) => comment.dishId === parseInt(match.params.dishId,10))} />
      );
    };

Single Page Applications

In traditional websites so far, you may be requesting for access to a particular page. For example, you will be requesting for an index to an HTML page when you navigate to the website either by clicking on a link or by typing the address of the website into the address bar of your browser. So typically, the index.html page is the first one that your fetch when you visit a website. When the page is downloaded from the server to your browser, and then this will be displayed in your browser. Now, this may include not just the index.html page but also other resources that may be needed to be downloaded in order to construct the index.html page. But now, if you navigate to another page in your website, say for example, another page like contactus.html, this will result in your browser sending another request to the server to fetch the second page. So it will initiate an entire requested server and then all the resources needed for constructing the second page will have to be downloaded from the server.

So as you move from one page to another page, it will involve every new page to be loaded from the server and this would involve a roundtrip time to the server to fetch all the resources required for constructing those pages. Now, imagine that your website has many pages then obviously, every single piece that your web page requires for rendering will require a full roundtrip time to the servers.

What you would notice often is that many of these pages have a lot in common. Perhaps for example, the header, the footer and some other piece of information, but still every single new page request will require you to go and fetch the entire page from the server. Now with the use of caching on the browser site, you can mitigate some of these problems by reusing the already fetched resources from your cache, but still every new page that you navigate to will require an entire page to be reloaded from the server site. Single-page applications approach this problem in a different way.

In a single-page application, typically, we have developed a web application. So, when the browser navigates to the website, then this will request for the web application to be downloaded from the server site. So this will be, for example, contained in a master page like index.html, which will trigger an entire set of assets that are required for rendering your web app to be downloaded to your client’s site. Now how these assets are packaged depends upon how you design your application and also, what framework you use to design your web application. You have one single large download at the start of your web application.

Subsequent changes to the client site, for example, initiated by a click on a link, will initiate a new request to the server site. But in this case, very often you’re only downloading some data, perhaps in the form of JSON data from the server site. So in this case, each of these may require only access to a server just to download the JSON data for example, which then may enable you to completely render the new view in your single-page application. So the initial page download, the initial application download, of course is always there but most subsequent interactions with the server will be simply for downloading data, typically in the form of JSON or XML depending on how you design your data format. Once the data is downloaded, this data can be then used to render the new view within your application. So in this circumstances, you will save a lot of roundtrip time to the server for downloading a lot of assets.

The significant feature of a single-page application. Also, single-page applications enable you to deliver a user experience that is more closer to what they see with desktop applications. Once the initial web app is downloaded, thereafter, most other interactions would seem like you are interacting with a desktop application. So you can mask a little bit of the initial download time for the web application by doing partial rendering from the server site itself.

[Image no longer available]

For more information,

  1. Single Page Apps in depth
  2. SPA and the Single Page Myth

Forms

A way of setting up forms in your React Application whereby your form information is directly tied into the state of your React component that is hosting the form. So, any changes that you make to your form imports will be immediately reflected into the state of your React component and so, the state of the form, or the information that the form is always reflected in that state of the React component can’t be retrieved from there.

Q.How does your React Application get input from the forms and then make use of it?

Before we understand that part, they have to realize that, every one of these form elements in HTML maintain their own state within DOM. And then they will update it based on user input. So in a text box for example, if you’re typing value, that input value that you type in will be retained in the DOM by that input box.

Now, we want to be able to connect that into our React components state, so that any changes to a box will be immediately reflected into React component state. Similarly, from the state, we can set the initial value for any of these form elements. So, how do we do this?

This is where the user control components in React come to aid. So, what is a Controlled Component? Controlled component makes the React component itself control the form that it renders. So when you include the form into the view of a React component, then you can easily tie in the React component state to the form, so that it will become the single source of truth. So the form information, whatever is the state of form will reflected into the state of the React component, so the form state and the components state will be match with each other. And this kind of implementation is what is referred to as a control component in React.

Now, with the control component, every state mutation, anytime you change any of the state, it will have to be reflected into the state of your React component. So you need appropriate handler functions that will enable change. So for example, if there is any change in a box, then that change should be immediately reflective to the state of your React component. Similarly, when the user clicks on the submit button, the submitted value should be captured inside your React component and thereafter can be processed as required by your React Application. So all this requires implementation of handler functions.

Form validations

Now for the form itself, I will use another property here called touched, which will keep track of whether a particular field has been touched or not.

Furthermore, we will validate the form each time the form is written, so we’ll implement a function called validate which will take in the Current values .

Now where do we invoke this? We will invoke this in the render function, because every time there is a change in your input fields, your form will be rerendered. And so that will be the appropriate time for you to carry out the check. And if there is an error in any one of them, the errors string or errors object that is returned from here will contain the error message in the corresponding strings image.

// Different validations
const required = (val) => val && val.length;
const maxLength = (len) => (val) => !(val) || (val.length <= len);
const minLength = (len) => (val) => val && (val.length >= len);
const isNumber = (val) => !isNaN(Number(val));
const validEmail = (val) => /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(val);

1.Controlled forms

So, since this is tied to the state of the React Application, the submission of the Form should be handled within the React Application. Not only that, whenever anything is changed in any of these elements, that should be reflected by changing the state of the component to reflect whatever is in the box here.

In the code, we will implement two different methods here.

  1. handleInputChange, which will receive the event as a parameter.
  2. handleSubmit which also receives the event as a parameter.

So, when you click on the Submit Button, the handler Submit should the called. Then when the Form is submitted

So in the handleInputChange method, we’ll make sure that this is invoked upon any change to any input value in our form. When this is invoked, then we will retrieve the target input from the event that has just been parsed in.

Now, how do we tie these two together? So to tie these two together, in your form for each of these items, for each of these inputs, I need to tie the onChange to this handleInputChange, so onChange. So whenever this input is changed, any change is made to the input, then this will result in a call to the handleInputChange, which will reflect the change in the input value back to the state of my form there

2 <FormGroup row>
                    <Label htmlFor="firstname" md={2}>First Name</Label>
                    <Col md={10}>
                        <Input type="text" id="firstname" name="firstname"
                            placeholder="First Name"
                            value={this.state.firstname}
                            valid={errors.firstname === ''}
                            invalid={errors.firstname !== ''}
                            onBlur={this.handleBlur('firstname')}
                            onChange={this.handleInputChange} />
                        <FormFeedback>{errors.firstname}</FormFeedback>
                    </Col>
                </FormGroup>
                <FormGroup row>
                    <Label htmlFor="lastname" md={2}>Last Name</Label>
                    <Col md={10}>
                        <Input type="text" id="lastname" name="lastname"
                            placeholder="Last Name"
                            value={this.state.lastname}
                            valid={errors.lastname === ''}
                            invalid={errors.lastname !== ''}
                            onBlur={this.handleBlur('lastname')}
                            onChange={this.handleInputChange} />
                        <FormFeedback>{errors.lastname}</FormFeedback>
                    </Col>
                </FormGroup>

2.Uncontrolled forms

Sometimes you will wish to have a very simple form with a very limited amount of interaction of that with your React component. In that case an uncontrolled form is a much easier way of setting up forms within your React application.

Now this approach of using uncontrolled forms is a lot more easier in situations when you are mixing your React application code with non-React code. So maybe you have a project that is already setup with some non-React part, and then you’re adding in React components or React elements to that project to set up some parts of the project.

So how do we retrieve this information? Now every, DOM form element has a ref associated with it, from which you can easily use thatch to extract their HTML form data into your application.

So, you see that when retrieving the values directly from the DOM and then using that here and then alerting, and then we’ll see

Now, since we are using this inside reactstrap. Reactstrap already uses ref for something else. So, in reactstrap components input we should use innerRef, instead of Ref here, innerRef here. So, we’ll say innerRef equal to input this.username equal to input. So, that is how you retrieve the information from inside your input field.

<FormGroup>
        <Label htmlFor="username">Username</Label>
        <Input type="text" id="username" name="username"
         innerRef={(input) => this.username = input} />
</FormGroup>

<FormGroup>
        <Label htmlFor="password">Password</Label>
        <Input type="password" id="password" name="password"
         innerRef={(input) => this.password = input}  />
</FormGroup>

For more information,

  1. Controlled Components
  2. reactstrap Form
  3. Controlled / Uncontrolled React Components
  4. Controlled and Uncontrolled Input Values in React
  5. Controlled and uncontrolled form inputs in React don’t have to be complicated
  6. How to Work with Forms, Inputs and Events in React
  7. Some Thoughts On Forms in React
  8. Instant form field validation with React’s controlled inputs

For GitHub repository, https://github.com/kakabisht/React_Course_assignments

For the following blog on react-redux, https://programmerprodigy.code.blog/2020/08/16/introduction-to-redux/