Skip to main content

React JS Form Validation, React Props Validation ES6 Tutorials With Examples

React Props Validation ES6 Overview

Validation is a important part of frontend application, here, we'll discuss about React JS component props validation. There are some common points which we'll learn in this post.
  • How to pass props and how to use spread operator
  • How to set type of props
  • How to make props mandatory or optional
  • How to set the default props
  • What is state,props and state vs props
  • Stateless vs Stateful Components
  • setState vs forceUpdate ReactJS function

ReactJS State VS Props

A state is mutable and maintains the data. We should avoid using more state to improve application performance. We can set the initial state in constructor and setState or forceUpdate functions can be used to update the state.
A prop is immutable and props are read only, means we can't update props directly. State is becomes props when pass parent to child component. We can set the default props through defaultProps.
ReactJs State and Props Example
import React,{Component} from 'react';
import PropTypes from 'prop-types';

class App extends Component{
    render(){
        return(
            <div>
             <CounterContainer startTimer='true'/>
            </div>
        )
    }
}

class CounterContainer extends Component{
    constructor(props){
        super(props);
        //set initial state 
        this.state={
            counter:props.counter 
        }
        this.onClick=this.onClick.bind(this);
    }

    onClick(){
      this.setState({counter:counter+1})
    }

    render(){
        const {counter}=this.state;
        const {startTimer}=this.props;
        return(
            <div>
                <button name="counterbtn">counter</button>
                <Counter counter={counter}/>
            </div>
        );
    }
}

export default CounterContainer;

const Counter=(props)=>{
  return(
      <div>{props.counter}</div>
  );
}

export default Counter;
Here, there is a component Counter and a container Countercontainer. In container, we have an initial state i.e. counter and that counter state is passed in child component i.e. Counter.

How to use spread operator with props

Spread operator is an ES6 feature which is very useful nowadays. It provides a feature to pass props dynamically.Means when we are not sure about the number of props, we must use spread operator. This spread operator can be used to pass props or parameters in a function. It used as three dots (...). Let's take an example of Input component, Input field has multiple properties. There are two ways to pass props, first pass props as props properties and other pass props as spread operator dynamically which is followed in live applications.

Pass props without spread operator
 import React, { Component } from "react";
import PropTypes from "prop-types";

class Input extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    const { placeholder, min, max, className } = this.props;
    return (
      <div>
        <input
          type="text"
          placeholder={placeholder}
          min={min}
          max={max}
          className={className}
        />
      </div>
    );
  }
}

class App extends Component {
  render() {
    return (
      <div>
        <Input placeholder="enter name" min="10"
        max="50" className="input" />
      </div>
    );
  }
}

export default App;
Here's, we are passing props as component props properties. Here, there is a problem if we want to add new props, we have to make changes in lower level component i.e. Input component which is not a good practice.

Spread Operator Props Example:
 import React, { Component } from "react";
 import PropTypes from "prop-types";

 class Input extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        <input type="text" />
      </div>
    );
  }
 }

 class App extends Component {    
  render() {
      const elementProps={
        placeholder='enter name',
        min:10,
        max:50,
        className:'input'        
    }
    return (       
      <div>
        <Input {...elementProps}/>
      </div>
    );
  }
 }
Here's, we are passing props dynamically using spread operator. Here's, good point is that we can add new props without any make any changes in lower level component i.e. Input component. This is good practice to pass props which a standard followed in IT industry.

Stateless vs Stateful Components: There are mainly two types of components stateless and stateful.


Stateless Component: a dumb component and doesn't maintain state is called stateless component. In application, we have to identify which component will make the stateless component, like header, footer or a  list component to display records can be a stateless component. Keep in mind, stateless component should be called through stateful component or container.


Stateless ReactJS Component Example
import React, { Component } from "react";

const Footer = props => {
  return (
    <div>
      <div>{props.heading}</div>
      {this.props.children}
    </div>
  );
};

const Header = props => {
  return (
    <div>
      <div>{props.heading}</div>
      {this.props.children}
    </div>
  );
};

class App extends Component {
  render() {
    return (
      <div>
        <Header heading="heading">
          <div>Home</div>
          <div>Products</div>
          <div>About Us</div>
          <div>Contact US</div>
        </Header>
        <div>
          //component is rendered here through routing
          <div>{this.props.children}</div>
        </div>
        <Footer heading="heading">
          <div>Contact Us</div>
          <div />
          <div>About Us</div>
          <div>Contact US</div>
        </Footer>
      </div>
    );
  }
}
export default App;
Here's, Header and Footer are stateless component.

Stateful Component: a smart component and maintain state is called stateful component. A state is used for internal communication inside component, we can track the previous value and current value. Avoid stateful component if you don't need. Component will re-render whenever state is changed. Click here to ReactJS component lifecycle.

What is the use of default Props and how to pass default Props

Default props are very useful in the application when we don't want to make the props mandatory and need to set the default value of that props, in that case, default props will fulfill the need. Component.defaultProps is the syntax to pass default props.
Default Props Example
import React, { Component } from "react";
import PropTypes from "prop-types";

class Input extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    const { placeholder, min, max, className } = this.props;
    return (
      <div>
        <input
          type="text"
          placeholder={placeholder}
          min={min}
          max={max}
          className={className}
        />
      </div>
    );
  }
}

Input.defaultProps = {
  placeholder: "enter value",
  min: 5,
  max: 30,
  className: "input"
};

class App extends Component {
  render() {
    return (
      <div>
        <Input />
      </div>
    );
  }
}
export default App;
Here's, there are some default props placeholder, min, max, and className. In App component, we are not passing props from parent component so in child component Input, we have default props which are renderd.

React Props Validation ES6 or React PropTypes ES6 

Here's, we'll see how to set PropTypes and how to validate component props. ReactJS library provides PropTypes, we can also add library 'prop-types'.
import React, { Component } from "react";
import PropTypes from "prop-types";

class Input extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    const { placeholder, min, max, className, size, 
    defaultValue } = this.props;
    return (
      <div>
        <input
          type="text"
          placeholder={placeholder}
          min={min}
          max={max}
          className={className}
        />
      </div>
    );
  }
}

Input.defaultProps = {
  placeholder: "enter value",
  min: 5,
  max: 30,
  className: "input",
  size: "large"
};

Input.propTypes = {
  placeholder: PropTypes.string,
  min: PropTypes.number,
  max: PropTypes.number,
  className: PropTypes.string.isRequired,
  size: PropTypes.oneOfType(["large", "small"]),
  defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
};

class App extends Component {
  render() {
    return (
      <div>
        <Input />
      </div>
    );
  }
}
export default App;
Here's, all the props have types as placeholder type is the string which is optional and className type is the string which is mandatory props which we need to pass from the parent component. We can also set the more than one type of props as size and defautValue have two types as string and number and size have custom types as large and small. It means size props will only accept large and small types. Click here to learn ReactJS Application Architecture.

setState() vs forceUpdate() ReactJS Functions

Both methods are used to re-render the component. Generally, setState() function is used to update the value and component will re-render. There is a question comes to mind if we have already a setState function why do we need other forceUpdate function. A setState function is used within the component scope to re-render the component but a forceUpdate function is used out of the scope of the component to re-render the component. The forceUpdate will trigger the normal lifecycle methods for child components, including the shouldComponentUpdate() method of each child. React will still only update the DOM if the markup changes. A forceUpdate function is useful when we want to use a third-party library with ReactJS and need to re-render the component.
React is unaware of our state mutations so we have to explicitly trigger the re-render by calling forceUpdate(). A good example of using this.forceUpdate is the integration with other library like D3.js. D3 has its own data sets so assume that if something changes in D3 dataset then it needs to tell React that 'Hey! React I change some of my stuff and now I need to just re-render' so D3 will callback out react by using forceUpate().

setState vs forceUpdate Example
Here's an example of what I am talking about. I'm working with Vis.js, and their DataSet object allows you to add data to an existing data set - nodes and edges.
import React, { Component } from "react";
import PropTypes from "prop-types";

class ForceUpdateExample extends Component {
  constructor(props) {
    super(props);
    this.state={message:''}
    onChange=this.onChange.bind(this);
  }

  onChange(evet){
    this.setState({message:evt.target.value})
  }
 
 passDataToGraph(nodes,edges){
    // call forceUpdate function
    this.state.graphData.nodes.add(nodes);
    this.state.graphData.edges.add(edges);
    this.forceUpdate();
 }
 
  render() {
    const {message}=this.state;
    return (
      <div>
        <input type="text" onChange={this.onChange}/>
        {message}
      </div>
    );
  }
}
export default ForceUpdateExample;

Points to be noted
  • Never update the state directly as this.state.value='value', always use setState function to update the state as setState({value:'value'}).
  • State should be avoid if you don't need.
  • Always use shouldComponentUpdate function to avoid useless re-rendering
  • Follow spread operator to pass props parent to child component
  • Remove imported libraries if not in use

Comments

Popular posts from this blog

React Redux Tutorials: React Redux Data Flow and Redux Lifecycle Methods With Examples

React Redux Data Flow and Redux Lifecycle Methods Overview What is Redux and why do we need Redux Redux is an open source JavaScript library which is designed for maintaining application state. Redux JS is a powerful and popular library nowadays. The command to install Redux library npm install redux --save . Nowadays JavaScript single-page applications are very popular and powerful. As the requirements for single-page applications have become complicated, our code must manage more state than ever before. This state can include server responses and cached data, as well as locally generated data that has not yet been persisted to the server. Front-end state is also increasing in complexity, as we need to manage active routes, selected tab, spinners, pagination controls etc. That's why we need Redux. click here to learn React Redux Architecture, folder structure. Three Principles of Redux: Changes are made with pure functions You write pure reducers to specify

React Redux Application Structure, Architecture and React Folder Structure Best Practices

React Redux Application Structure, Architecture and  React Folder Structure Best Practices: There some questions comes our mind when we are going to create a new react redux application structure from scratch. What folder structure should be followed especially when we are implementing a large react redux application . How to connect react with redux  What should be the naming convention of folder and react js files. What are the best practices of react redux project structure. The structure might be different for each of us but I am sharing the standard react redux application structure which is followed by most of the UI developers in IT industry. High Level React Redux Application Architecture There are many folders and files in above application screen shot, let discuss one by one. The application name is REACTWEBAPP and folders are config, public, script, server, src, reducers, sagas, store and package.json. Config: react redux application configurations

ReactJS Routing And Single Page Application Tutorial

React Router: ReactJS Single Page Application Why do we need React Router Nowadays single page application is the most popular. For making single page application, we need to react router. Single page application is very powerful and provides performance features as well. What is React Router React router is a library, it provides routing feature through which we can redirect from one page to another page. Mainly there are two types of routing. 1. Browser Specific routing: In general or e-commerce web application have browser routing and it helps in search engine optimization. npm command to install routing package npm install react-router --save . --save is used to save the package entry in project specific package.json file. import React from 'react'; import ReactDOM from "react-dom"; import { Router, Route, Link, browserHistory, IndexRoute } from 'react-router'; import Home from './Home'; import About from './About'; import