Build a React Form as a Pro || Advance Level
Hello Developer!
Here in this article, We will learn how to make a input form like a pro player. Here we created to files App.js and InputCom.js In App Component we use data useState hook to manage all the necessary field, this data we will use to process the input with backend server. We created a btnHandler function to handle the submit button. We are used an another formList useState hook to manage input type attributes like type, name, placeholder etc and we are use map method to loop InputCom component which is manage the input value. We are created a inputValue funtion to taking input value from child component (InputCop) to parent component (App) through props.
import { useState } from "react"; import { InputCom } from "./InputCom"; export default function App() { const [data, setData] = useState({ name: "", email: "", password: "" }); const inputValue = (name, value) => { setData({ ...data, [name]: value }); }; const btnHandler = () => { const { name, email, password } = data; alert(`Name is ${name} and Email is ${email} and password is ${password} `); }; const [formList, setFormList] = useState([ { name: "name", type: "text", placeholder: "Enter Your Name" }, { name: "email", type: "email", placeholder: "Enter Your Email" }, { name: "password", type: "password", placeholder: "Enter Your Password" } ]); return ( <> {formList.map((item, index) => { return ( <InputCom key={index} name={item.name} type={item.type} placeholder={item.placeholder} inputValue={inputValue} /> ); })} <br /> <button onClick={btnHandler}>Submit</button> </> ); }
We are created InputCom component to manage input. We created a text useState hook to control the input value. textHandler function to handle onChange event.
import React, { useState } from "react"; export const InputCom = (props) => { const [text, setText] = useState(""); const textHandler = (e) => { setText(e.target.value); props.inputValue(e.target.name, e.target.value); }; return ( <input type={props.type} name={props.name} placeholder={props.placeholder} value={text} onChange={textHandler} /> ); };
So this is all we learn in this article. If you have any doubt, you can react us at playerofcode@gmail.com