Home React 06. Forms
Post
Cancel

React 06. Forms

HTML form 요소들은 React의 다른 DOM 요소와 다르게 작동한다. form 요소는 자연스럽게 내부 상태를 가지게 되고, React에서는 form 요소의 내부 상태를 State로 관리할 수 있다.

Controlled Components

HTML form 요소들은 사용자 입력을 기반으로 내부 상태를 업데이트 한다. React에서는 오직 setState()를 통해서 내부 상태를 업데이트 한다.

React는 form 요소의 내부 상태를 제어하고, 변경이 감지되면 렌더링한다. 이처럼 React에서 값을 제어하는 form 요소를 Controlled Components라 한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    class NameForm extends React.Component {
        constructor(props) {
            super(props);

            this.handleChange = this.handleChange.bind(this);
            this.handleSubmit = this.handleSubmit.bind(this);
        }

        handleChange(e) {
            this.setState({ value: event.target.value});
        }

        handleSubmit(e) {
            e.preventDefault(); // Submit 이 후 새 페이지로 넘어가는 것 을 방지함
            alert('A name was submitted: ' + this.state.value);
        }

        render() {
            return (
                <form onSubmit={this.handleSubmit}>
                    <label>
                    Name: <input type="text" value={this.state.value} onChange={this.handleChange} />
                    </label>
                    <input type="submit" value="Submit">
                </form>
            );
        }
    }

Controlled Component를 사용하면 입력 값은 항상 React State에 의해 결정된다.

select Tag

React에서는 selected 값을 State를 통해서 지정한다.

  • HTML
1
2
3
4
5
6
    <select>
        <option value="grapefruit">Grapefruit</option>
        <option value="lime">Lime</option>
        <option selected value="coconut">Coconut</option>
        <option value="mango">Mango</option>
    </select>
  • React
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
    class FlavorForm extends React.Component {
        constructor(props) {
            super(props);
            this.state = {value: 'coconut'};

            this.handleChange = this.handleChange.bind(this);
            this.handleSubmit = this.handleSubmit.bind(this);
        }

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

        handleSubmit(event) {
            alert('Your favorite flavor is: ' + this.state.value);
            event.preventDefault();
        }

        render() {
            return (
            <form onSubmit={this.handleSubmit}>
                <label>
                Pick your favorite flavor:
                <select value={this.state.value} onChange={this.handleChange}>
                    <option value="grapefruit">Grapefruit</option>
                    <option value="lime">Lime</option>
                    <option value="coconut">Coconut</option>
                    <option value="mango">Mango</option>
                </select>
                </label>
                <input type="submit" value="Submit" />
            </form>
            );
        }
    }
This post is licensed under CC BY 4.0 by the author.