Goals

- Build forms with React

- Understand controlled components

 

 

## Forms

- HTML form works !== DOM form in react 

- In React : function that handle submit of form, 

             finction that access to the user data

- [Controlled Components]

 

 

## Controlled Components

- In HTML, form elements maintain their own state and update it when user types

- In React, mutable state is kept in the state of components, and only update with setState()

 

- How can we control form input state in React?

    - React controls : What is shown (the value of the component)

                       What happen when user types ('this' gets kept in state)

                       -> [Controlled Components]



 

## How the controlled form works

- handleChange(){ 

    // handle every keystroke

    this.setState({

        fullName: evt.target.value

    }); 

}

import React, { Component } from 'react';


class Form extends Component {
    constructor(props) {
        super(props);
        this.state = { username: "" };
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);

    }

    handleChange(evt) {
        this.setState({ username: evt.target.value });
    }

    handleSubmit(evt) {

        evt.preventDefault(); //prevent refreshing
        alert(`You typed ${this.state.username}`);
        this.setState({ username: "" });
    }

    render() {
        return (
            <div>
                <h1>Form</h1>
                <form onSubmit={this.handleSubmit}>
                    <input
                        type="text"
                        value={this.state.username}
                        onChange={this.handleChange}
                    />

                    <button>Submit</button>
                </form>
            </div>
        );
    }
}


export default Form;