[React Example] 토글형식버튼 만들기

youngseo·2022년 7월 6일
0

REACT

목록 보기
16/52

토글형식버튼 만들기

function FollowButton() {
  return React.createElement("div", {}, "Follow");
}

const domContainer = document.querySelector('#follow_button_container');
ReactDOM.render(React.createElement(FollowButton), domContainer);

현재의 상태에서 FollowButton을 누르는 경우 Follow여부에 따라 Follow 와 following이 보이는 컴포넌트를 만들어보겠습니다.

1. 동작 추가하기

function FollowButton() {
  const [following, setFollowing] = React.useState(false)
  return React.createElement("div", {
    onClick: () => setFollowing(!following)
  }, following ? "following" : "Follow");
}
  • const [following, setFollowing] = React.useState(false)

    • following이라는 변수를 초기값 false로 생성합니다.
    • 그리고 이 following이라는 변수의 상태값을 변경하기 위해 setFollowing이라는 함수를 사용합니다.
  • return React.createElement("div", {}, following ? "following" : "Follow");

    • following인 경우 following을 그렇지 않은 경우 Follow를 내보냅니다.
  • onClick: () => setFollowing(!following)

    • onClick일때 setFollowing 함수를 실행해서 현재값과 반대되는 값을 넣어줍니다.

0개의 댓글