뭐든 즐기면서 ;)

React Form2 / React Select 본문

카테고리 없음

React Form2 / React Select

Tada.*+ 2021. 11. 26. 21:53
728x90

1. select 태그

  • React에서 select 값 선택은 selected 대신에 value를 이용합니다.
  • onChange를 통하여 state를 업데이트 합니다.
  • // 기존 html 형식
    <select>
      <option value="grapfruit">포도</option>
      <option selected value="coconut">코코넛</option>
      <option value="banana">바나나</option>
    </select>
  • 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) {
            event.preventDefault();
            console.log('value', this.state.value);
        }
    
        render() {
            return (
              <form onSubmit={this.handleSubmit}>
                  // React에서는 value를 사용합니다.          
                  <select value={this.state.value} onChange={this.handleChange}>
                      <option value="grapefruit">포도</option>
                      <option value="coconut">코코넛</option>
                      <option value="banana">바나나</option>
                  </select>
                  <input type="submit" value="확인" />
              </form>
            );
        }
    }

2. select multiple

  • select 태그에 multiple 옵션을 허용한다면 value 어트리뷰트에 배열을 전달할 수 있습니다.
  • // 기본
    <select multiple={true} value={['B', 'C']}>
  • // state에 배열로 넣는 방법
    // Array.from 함수와 event.target.selectedOptions을 이용합니다.
    handleChange(event) {
        console.log('selectedOptions', event.target.selectedOptions);
    
        let values = Array.from(
            event.target.selectedOptions,
            ( option => option.value)
        );
        this.setState({value: values});
    }
    
    handleSubmit(event) {
        event.preventDefault();
        console.log('value', this.state.value);
    }
    
    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <select multiple={true} value={this.state.value} onChange={this.handleChange}>
                    <option value="grapefruit">포도</option>
                    <option value="coconut">코코넛</option>
                    <option value="banana">바나나</option>
                </select>
                <input type="submit" value="확인" />
            </form>
        );
    }

 

React selected / React multiple / React Select multiple

 

이전 글: https://tadaiswhatever.tistory.com/41

728x90
Comments