Friday, October 2, 2020

Handling Form Inputs in React in less lines of code

 Handling Form Inputs in React (less lines of code)




import React, { useState } from 'react'

const MyFormObject = () => {

    const USER = {
        id: "1",
        name: "Dinesh",
        salary: 10000
    }

    const [usersetUser] = useState(USER)

    const onSubmitHandler = (event=> {
        event.preventDefault();
        console.log(user)
    }

//handling Form Input 
    const handleInput = (event=> {
        let name = event.target.name;
        let value = event.target.value;
        setUser((preValue=> {
            console.log(preValue);
            return {
                ...preValue//Spread Operator 
                [name]: value,
            };
        }
        )
        console.log(event.target.value)
    }

    return (
   <> //Fragment
    <form onSubmit={onSubmitHandler}>

       UserID:   
<input type="text" name="id" value={user.id} onChange={handleInput} /><br />
       Name 
<input type="text" name="name" value={user.name} onChange={handleInput} /><br />
       Salary 
<input type="text" name="salary" value={user.salary} onChange={handleInput} /><br />
                
<input type="submit" value="Submit" />

    </form>
  </>
    )

}

export default MyFormObject


App.js Code Snippet:

const LearningComponent = () => {
  return (
    <div>
     <h1> Learning Component </h1>
      <MyFormObject />
    </div>
  )
}

export default App;

3 comments:

  1. Innovative tools and thoughtful layout improve usability, and CNAME Lookup delivers precise CNAME results quickly. Users can explore domain setups, verify records, and detect issues seamlessly while interacting with a platform that balances technical accuracy, clarity, and ease of use perfectly.

    ReplyDelete
  2. Uniquely, the port checker
    platform turns complex port testing into a simple, enjoyable process. Fast results, precise diagnostics, and a clean interface make it easy for users to monitor connectivity efficiently, ensuring anyone can handle network troubleshooting confidently without stress.

    ReplyDelete
  3. Enthralling website layout inspires engagement, and what is my sun sign provides precise personality analysis. Users can discover character traits, emotional tendencies, and compatibility effortlessly, while the interactive interface, informative content, and appealing design make exploring astrology enjoyable, enlightening, and highly rewarding naturally.

    ReplyDelete

Create a Digital Clock using HTML and JavaScript

Create a Digital Clock using HTML and JavaScript  <! DOCTYPE html> < html > < head > ...

Followers

Search This Blog

Popular Posts