Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forms as functional components with react

If I want to make a functional component that will contain a form ,to login for example, and I want to contain the state in App component and Login will be its child, can I mutate the state in App using the form in Login child?

like image 677
Alexander Avatar asked Nov 28 '18 12:11

Alexander


People also ask

Should you use form element in React?

In most cases, we recommend using controlled components to implement forms. In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.

What is form component in React?

Forms are an integral part of any modern web application. It allows the users to interact with the application as well as gather information from the users.


2 Answers

import React, {useState} from 'react';

function Submit() {

    const [inputField , setInputField] = useState({
        first_name: '',
        last_name: '',
        gmail: ''
    })

    const inputsHandler = (e) =>{
        setInputField( {[e.target.name]: e.target.value} )
    }

    const submitButton = () =>{
        alert(inputField.first_name)
    }

    return (
        <div>
            <input 
            type="text" 
            name="first_name" 
            onChange={inputsHandler} 
            placeholder="First Name" 
            value={inputField.first_name}/>

            <br/>

            <input 
            type="text" 
            name="last_name" 
            onChange={inputsHandler} 
            placeholder="First Name" 
            value={inputField.last_name}/>

            <br/>

            <input 
            type="gmail" 
            name="gmail" 
            onChange={inputsHandler} 
            placeholder="Gmail" 
            value={inputField.gmail}/>

            <br/>

            <button onClick={submitButton}>Submit Now</button>
        </div>
    )
}

export default Submit
like image 93
Mehedi Setu Avatar answered Oct 15 '22 07:10

Mehedi Setu


Yes. Pass two props an object data and a method onChange to Login from App. data will set the values for the form in Login.

Fire onChange with updated form values if there is any change in Login form.

Handle it in App and update its state which will then flow down to Login as data.

like image 34
Easwar Avatar answered Oct 15 '22 06:10

Easwar