Skip to main content

Controlled Form-Input in React-JS


Controlled components have functions that govern the data passing into them on every onChange event, rather than grabbing the data only once, e.g., when you click a submit button. This data is then saved to the state and updated with setState() method. This makes components have better control over the form elements and data.
A controlled component takes its current value through props and notifies the changes through events or callbacks like an onChange event. A parent component "controls" these changes by handling the callback and managing its own state and then passing the new values as props to the controlled component. It is also called a "dumb component."

Code of Controlled Component in React JS:-

Now i am implementing addition program to implement react-js controlled component.

import React, { Component } from 'react';  
export class Controlledcomponent extends React.Component
{
    constructor(props) {  
        super(props);  
        this.state = {value:'',value1:''}
        this.handleSubmit = this.handleSubmit.bind(this); 
        this.handleSubmit1 = this.handleSubmit1.bind(this);   
        this.updateSubmit = this.updateSubmit.bind(this);  
         
    } 
    handleSubmit(event)
    {
        this.setState({value:event.target.value});
    }
    handleSubmit1(event)
    {
        this.setState({value1:event.target.value});
    }
    updateSubmit(event) {  
       var c = parseInt(this.state.value)+parseInt(this.state.value1);
       alert("Result is "+c);
        event.preventDefault();  
    }   

    render() {  
        return (  
          <form onSubmit={this.updateSubmit}>  
            <h1>controlled Form Example</h1>  
            <label>Num1:  
                <input type="text" onChange={this.handleSubmit}  />  
            </label>  
            <label>Num2 :  
                <input type="text" onChange={this.handleSubmit1}   />  
            </label>  
            
            <input type="submit" value="Submit" />  
          </form>  
        );  
      }  

}


Same Program using Arrow Function Without dynamic binding:

import React from "react";
export class AdditionControlledClassComponent extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state={a:'',b:'',result:''};
     //   this.add=this.add.bind(this);
      //  this.enterNum1 = this.enterNum1.bind(this);
       // this.enterNum2 = this.enterNum2.bind(this);

    }
    enterNum1=(e)=>
    {
            this.setState({a:e.target.value})
    }
    enterNum2=(e)=>
    {
        this.setState({b:e.target.value})
    }
    add=(e)=>
    {
        var c = parseInt(this.state.a)+parseInt(this.state.b);
        this.setState({result:c});
        e.preventDefault();
    }
    render()
    {
        return(<div>
        <form onSubmit={this.add}>
          <input type="text" onChange={this.enterNum1} placeholder="Enter First Number" />
          <br/>
          <input type="text" onChange={this.enterNum2} placeholder="Enter First Number" />
          <br/>
          <input type="submit" value="Add" />
        </form>
          {this.state.result}
        </div>)
    }

}

Example of SI Component:-

import React from "react"
export class SimpleCalc extends React.Component
{
    constructor(props)
    {
       
        super(props);
        this.state = {p:'',r:'',t:''}
        this.enterP=this.enterP.bind(this);
        this.enterT=this.enterT.bind(this);
        this.enterR = this.enterR.bind(this);
        this.calc=this.calc.bind(this);

    }
    enterP(event)
    {
        this.setState({p:event.target.value});
       
       
    }
    enterR(event)
    {
        this.setState({r:event.target.value});
    }
    enterT(event)
    {
        this.setState({t:event.target.value});
    }

    calc(event)
    {
        var si = (parseFloat(this.state.p)* parseFloat(this.state.r)* parseFloat(this.state.t))/100;
        alert("Result is "+si);
    }
    render(){
        return(
         <form>
              <input type="text"  placeholder="Enter value of P" onChange={this.enterP} />
              <br/>
              <input type="text" placeholder="Enter value of R" onChange={this.enterR} />
              <br/>
              <input type="text"  placeholder="Enter value of T" onChange={this.enterT} />
              <br/>
              <input type="submit" value="click" onClick={this.calc} />

         </form>

        );

    }

}

Display Result under Textfield:-

import React from "react"
export class SimpleCalc extends React.Component
{
    constructor(props)
    {
       
        super(props);
        this.state = {p:'',r:'',t:'',si:''}
        this.enterP=this.enterP.bind(this);
        this.enterT=this.enterT.bind(this);
        this.enterR = this.enterR.bind(this);
        this.calc=this.calc.bind(this);

    }
    enterP(event)
    {
        this.setState({p:event.target.value});
       
       
    }
    enterR(event)
    {
        this.setState({r:event.target.value});
    }
    enterT(event)
    {
        this.setState({t:event.target.value});
    }

    calc(event)
    {
        var si = (parseFloat(this.state.p)* parseFloat(this.state.r)* parseFloat(this.state.t))/100;
        this.setState({si:si})
        //  alert("Result is "+si);
        event.preventDefault();
    }
    render(){
        return(
         <form>
              <input type="text"  placeholder="Enter value of P" onChange={this.enterP} />
              <br/>
              <input type="text" placeholder="Enter value of R" onChange={this.enterR} />
              <br/>
              <input type="text"  placeholder="Enter value of T" onChange={this.enterT} />
              <br/>
              <input type="submit" value="click" onClick={this.calc} />
              <br />
               <input type="text" value={this.state.si} />
         </form>

        );

    }

}                                                                                         


Calcuator Program in React Js:-

import React from "react";
export class ControllerformInput extends React.Component
{
 
    constructor(props)
    {
       
        super(props);
       
        this.state = {exp:'',c:''};
       
        this.updateSubmit = this.updateSubmit.bind(this);
        this.calc = this.calc.bind(this);
    }
   
   
     updateSubmit(event)
     {
     
        this.setState({exp:this.state.exp.concat(event.target.value)})
     
     
         event.preventDefault();
     }
     calc(event)
     {
        var s=this.state.exp;
        var t=0;
        for(var i=0;i<s.length;i++)
        {
         
         if(s[i]=='+')
         {
            if(i==1)
            {
            t = t+ parseInt(s[i-1]) + parseInt(s[i+1]);
            }
            else
            {
                t = t+parseInt(s[i+1]);
            }
           
         }
         else if(s[i]=='-')
         {
             if(i==1)
            {
            t = t+ parseInt(s[i-1]) - parseInt(s[i+1]);
            }
            else
            {
            t = t-parseInt(s[i+1]);
            }
           
         }
         else if(s[i]=='*')
         {
             if(i==1)
            {
            t = t+ parseInt(s[i-1]) * parseInt(s[i+1]);
            }
            else
            {
            t = t*parseInt(s[i+1]);
            }
           
         }
         else if(s[i]=='/')
         {
             if(i==1)
            {
            t = t+ parseInt(s[i-1]) / parseInt(s[i+1]);
            }
            else
            {
            t = t/parseInt(s[i+1]);
            }
         }

         
     }
     this.setState({'c':t});
     event.preventDefault();
    }
    render()
    {
     
        return(
            <div>
                <form >
                    <input type="text"  value={this.state.exp}  />
                    <br/>
                 
                    <br/>
                    <input type="submit" name="btnsubmit" value="1" onClick={this.updateSubmit}/>
                    <input type="submit" name="btnsubmit" value="2" onClick={this.updateSubmit}/>
                     <input type="submit" name="btnsubmit" value="+" onClick={this.updateSubmit}/>
                     <input type="submit" name="btnsubmit" value="-" onClick={this.updateSubmit}/>
                     <input type="submit" name="btnsubmit" value="=" onClick={this.calc}/>
                </form>
                <div>{this.state.c}</div>
            </div>
        );
    }
} 


Same Program using Eval :-

import React from "react";
export class ControllerformInput extends React.Component
{
 
    constructor(props)
    {
       
        super(props);
       
        this.state = {exp:'',c:''};
       
        this.updateSubmit = this.updateSubmit.bind(this);
        this.calc = this.calc.bind(this);
    }
   
   
     updateSubmit(event)
     {
     
        this.setState({exp:this.state.exp.concat(event.target.value)})
     
     
         event.preventDefault();
     }
     calc(event)
     {
        var s=this.state.exp;
     /*   var t=0;
        for(var i=0;i<s.length;i++)
        {
         
         if(s[i]=='+')
         {
            if(i==1)
            {
            t = t+ parseInt(s[i-1]) + parseInt(s[i+1]);
            }
            else
            {
                t = t+parseInt(s[i+1]);
            }
           
         }
         else if(s[i]=='-')
         {
             if(i==1)
            {
            t = t+ parseInt(s[i-1]) - parseInt(s[i+1]);
            }
            else
            {
            t = t-parseInt(s[i+1]);
            }
           
         }
         else if(s[i]=='*')
         {
             if(i==1)
            {
            t = t+ parseInt(s[i-1]) * parseInt(s[i+1]);
            }
            else
            {
            t = t*parseInt(s[i+1]);
            }
           
         }
         else if(s[i]=='/')
         {
             if(i==1)
            {
            t = t+ parseInt(s[i-1]) / parseInt(s[i+1]);
            }
            else
            {
            t = t/parseInt(s[i+1]);
            }
         }

         
     }*/
     this.setState({'c':eval(s)});
     event.preventDefault();
    }
    render()
    {
     
        return(
            <div>
                <form >
                    <input type="text"  value={this.state.exp}  />
                    <br/>
                 
                    <br/>
                    <input type="submit" name="btnsubmit" value="1" onClick={this.updateSubmit}/>
                    <input type="submit" name="btnsubmit" value="2" onClick={this.updateSubmit}/>
                     <input type="submit" name="btnsubmit" value="+" onClick={this.updateSubmit}/>
                     <input type="submit" name="btnsubmit" value="-" onClick={this.updateSubmit}/>
                     <input type="submit" name="btnsubmit" value="=" onClick={this.calc}/>
                </form>
                <div>{this.state.c}</div>
            </div>
        );
    }
}


Radiobuttonexample in React Js:-

import React from "react";
export class RadioExample extends React.Component
{
  
    constructor(props)
    {
       
        super(props);
        
        this.state = {a:'',b:'',c:'',o:''};
       
        this.updateSubmit = this.updateSubmit.bind(this);
        this.updateSubmit1 = this.updateSubmit1.bind(this);
        this.radioClick = this.radioClick.bind(this);
        this.calc = this.calc.bind(this);
    }
    
    
     updateSubmit(event)
     {
     
        this.setState({a:event.target.value})
        event.preventDefault();
     }
     updateSubmit1(event)
     {
     
        this.setState({b:event.target.value})
        event.preventDefault();
     }
     radioClick(event)
     {
     
        this.setState({o:event.target.value})
        //event.preventDefault();
     }
     calc(event)
     {
     if(this.state.o == "+")
     {
        this.setState({'c':parseInt(this.state.a)+parseInt(this.state.b)});
     }   
     else
     {
        this.setState({'c':parseInt(this.state.a)-parseInt(this.state.b)});
     }
     event.preventDefault();
    }
    render()
    {
      
        return(
            <div>
                <form>
                    <input type="radio" name="ope" value="+" onChange={this.radioClick}   />+
                    <input type="radio" name="ope" value="-" onChange={this.radioClick}  />-
                    <br></br>
                    <input type="text"  value={this.state.exp} placeholder="Enter First Number" onChange={this.updateSubmit}  />
                    <br/>
                    <input type="text"  value={this.state.exp} placeholder="Enter Second Number" onChange={this.updateSubmit1} />
                    <br/>
                    <input type="submit" name="btnsubmit" value="Calculate" onClick={this.calc}/>
                </form>
                <div>{this.state.c}</div>
            </div>
        );
    }
}

Function Component Example to create incremental:-

import { useState } from "react";

function ControlledFunctionComponentExample()
{

    const [a,setA] = useState(1);
   
    return(
     <div>
      <input type="button" onClick={() => setA(a+1)} value="click" /> 
     
      <p>{a}</p>
     </div>

    )
}

export default ControlledFunctionComponentExample;


Same program using the internal function:-

import { useState } from "react";

function ControlledFunctionComponentExample()
{

    const [a,setA] = useState(1);
    function fun()
    {
        setA(a+1);
    }
    return(
     <div>
      <input type="button" onClick={fun} value="click" /> 
     
      <p>{a}</p>
     </div>

    )
}

export default ControlledFunctionComponentExample;


function component with external function:-

import { useState } from "react";
function increment(n)
{
    return n+1;
}
function ControlledFunctionComponentExample()
{

    const [a,setA] = useState(1);
   
    return(
     <div>
      <input type="button" onClick={() => setA(increment)} value="click" /> 
     
      <p>{a}</p>
     </div>

    )
}

export default ControlledFunctionComponentExample;

Function Component Example in React Js for Swap Program:-

import { useState } from "react";

function Swap()
{

    var [a,setA] = useState(1);
    var [b,setB] = useState(1);
    function fun1(e)
    {
       
        setA(e.target.value);
    }
    function fun2(e)
    {
        setB(e.target.value);
       
    }
    function fun()
    {
     let temp = a;
     a=b;
     b=temp;
     setA(a);
     setB(b);

     
       
    }
   
    return(
     <div>
      <input type="text" onChange={(e) => fun1(e)}  />
      <br />
      <input type="text" onChange={(e) => fun2(e)}/>
      <br />
      <input type="button" onClick={fun} value="Swap" />
      <p>a={a},b={b}</p>
     </div>

    )
}

export default Swap;



Same Example using Class Component:-
import React, { useState } from "react";

export class Swap extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state = {a:'',b:''}
        this.handleInput = this.handleInput.bind(this);
        this.handleInput1 = this.handleInput.bind(this);
        this.handleClick = this.handleClick.bind(this);

    }
   
    handleInput(e)
    {
       
        this.setState({a:e.target.value});
    }
    handleInput1(e)
    {
        this.setState({b:e.target.value});
       
    }
    handleClick(e)
    {
     let temp = this.state.a;
     this.setState({'a':this.state.b});
     this.setState({'b':this.state.temp});
   

     
       
    }
   render()
   {
    return(
     <div>
      <input type="text" onChange={this.handleInput}  />
      <br />
      <input type="text" onChange={this.handleInput1}/>
      <br />
      <input type="button" onClick={this.handleClick} value="Swap" />
      <p>a={this.state.a},b={this.state.b}</p>
     </div>

    )
   }
}



Calculate Square Program using Controlled Functional Component:-

import { useState } from "react";

function Squarecom()
{
var [a,setA] = useState(0);
function setNumber(e)
{
   // alert(e.target.value);
     setA(e.target.value);

}
function calculate(e)
{
    setA(a*a);
   // alert(a);
    e.preventDefault();
}
return(
    <div>
            <form onSubmit={(e)=>calculate(e)}>
            <input type="text" onChange={(e)=>setNumber(e)}  />
            <br />
            <input type="submit" value="click" />
            </form>
        <p>{a}</p>
    </div>
); 



}

export default Squarecom;

Same Program using class Component:-

import React, { useState } from "react";

export class Squarecom extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state={'a':'','res':''};
        this.setNumber = this.setNumber.bind(this);
        this.calculate = this.calculate.bind(this);
    }

   setNumber(e)
{
   // alert(e.target.value);
     this.setState({'a':e.target.value});

}
 calculate(e)
{
    this.setState({'res':(parseInt(this.state.a)*parseInt(this.state.a))});

   // alert(a);
    e.preventDefault();
}
render()
{
    return(
    <div>
            <form onSubmit={this.calculate}>
            <input type="text" onChange={this.setNumber}  />
            <br />
            <input type="submit" value="click" />
            </form>
        <p>{this.state.res}</p>
    </div>
); 
}



}





  



Comments

Popular posts from this blog

Uncontrolled form input in React-JS

  Uncontrolled form input in React-JS? If we want to take input from users without any separate event handling then we can uncontrolled the data binding technique. The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM. Example of Uncontrolled Form Input:- import React from "react" ; export class Info extends React . Component {     constructor ( props )     {         super ( props );         this . fun = this . fun . bind ( this ); //event method binding         this . input = React . createRef ();...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...

DSA in C# | Data Structure and Algorithm using C#

  DSA in C# |  Data Structure and Algorithm using C#: Lecture 1: Introduction to Data Structures and Algorithms (1 Hour) 1.1 What are Data Structures? Data Structures are ways to store and organize data so it can be used efficiently. Think of data structures as containers that hold data in a specific format. Types of Data Structures: Primitive Data Structures : These are basic structures built into the language. Example: int , float , char , bool in C#. Example : csharp int age = 25;  // 'age' stores an integer value. bool isStudent = true;  // 'isStudent' stores a boolean value. Non-Primitive Data Structures : These are more complex and are built using primitive types. They are divided into: Linear : Arrays, Lists, Queues, Stacks (data is arranged in a sequence). Non-Linear : Trees, Graphs (data is connected in more complex ways). Example : // Array is a simple linear data structure int[] number...