자식 컴포넌트의 state을 부모 컴포넌트와 함께 사용하기

자식 컴포넌트에서 text가 존재하는지를 나타내는 hasText라는 state을 들고 있었고, 이것은 onKeyUp 이벤트 핸들러를 통해 set되고 있었다. 그리고 이 hasText라는 state가 부모 컴포넌트도 필요했고, 이 state을 이용해 버튼 컨트롤을 disable해야 하는 이슈가 있었다…

상황 정리

이슈 해결

import React, { useState } from 'react';

function App() {
  return (
    <div className="App">
      <Parent />
    </div>
  );
};

const Parent = (props) => {
  const [hasText, setHasText] = useState(false);
  
  return (
    <div class='parent'>
        <Child hasText={hasText} setHasText={setHasText} />
    </div>
  );
};

const Child = (props) => {
    const {hasText, setHasText} = props;
    function checkText() {
        ...
        const text = ...;
        if (text === '')    setHasText(false);
        else setHasText(true);
    }
    return (
        <div class='parent'>
            <button onKeyUp={() => {
                checkText()}
            }>
                send data to parent
            </button>
            {!hasText && <div className='placeholder'>댓글을 입력해주세요.</div>}
        </div>
    );
};