React/React 문법

[React]React에서 radio 버튼 사용하기

DevStory 2021. 8. 5.

이번 포스팅에서는 React에서 radio 버튼을 사용하는 방법에 대해 정리합니다.

 


radio 버튼을 클릭할 때마다 state 변경

radio 버튼을 클릭할때마다 this.state.selectValue의 값이 변경되는 코드입니다.

 

constructor

this.state.selectValue의 값을 "Mac"으로 초기화합니다.

constructor(props) {
  //...
  this.state = {
    selectValue: "Mac"
  };
}

 

handleChange

이벤트 핸들러 함수 handleChange를 작성합니다.

this.state.selectValue의 값을 이벤트가 발생한 타깃의 값으로 변경합니다.

handleChange = (e) => {
  console.log(`*****handleChange*****`);
  console.log(`선택한 값 : ${e.target.value}`);

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

 

input Element

render() 코드가 길어서 input Element만 설명합니다.

checked={this.state.selectValue === "Windows"} 는 this.state.selectValue의 값에 따라서 체크하는 용도와 컴포넌트가 마운트 될 때, this.state.selectValue의 초기값에 따라서 체크하기 위해서입니다.

onChange={this.handleChange} 는 라디오 버튼을 클릭할 때마다 handleChange 함수를 호출하여 state를 변경합니다.

<input id="Windows"
       value="Windows"
       name="platform"
       type="radio"
       checked={this.state.selectValue === "Windows"}
       onChange={this.handleChange} />

radio 버튼 동적으로 추가

radio 버튼을 동적으로 추가하는 코드입니다.

 

constructor

this.state.selectList는 동적으로 radio버튼을 추가하는 배열입니다.

this.state.selectValue의 값을 "Mac"으로 초기화합니다.

constructor(props) {
  super(props);

  this.state = {
    selectList: ["Windows", "Mac", "Linux"],
    selectValue: "Mac"
  };
}

 

동적으로 radio 버튼을 추가

this.state.selectList를 map() 함수로 순회하여 radio 버튼을 추가합니다.

<React.Fragment key={i}>...</React.Fragement> 태그로 input 태그를 감싸며, key를 설정합니다.

{this.state.selectList.map((value, i) => (
  <React.Fragment key={i}>
    <input
      id={value}
      value={value}
      name="platform"
      type="radio"
      checked={this.state.selectValue === value}
      onChange={this.handleChange}/>
      {value}
  </React.Fragment>
))}
반응형

댓글