리액트는 단방향으로만 데이터가 흐른다. 그래서 자식 <-> 자식 이렇게 데이터가 흐를 수 없다. 자식 => 부모 => 자식으로만 데이터가 흐른다. 그래서 자식 간 데이터를 주고 받으려면 부모가 props로 자식에 데이터를 주면 된다.
자식 컴포넌트 1 (온클릭에 props를 줘서 state를 담고 끌어올린다.)
const DiaryEditor = ({onCreate}) => {
const [state, setState] = useState({
author: "",
content: "",
emotion: 1,
});
const handleSubmit = () => {
onCreate(state.author, state.content, state.emotion);
};
return (
...
);
};
export default DiaryEditor;
부모 컴포넌트 (자식에서 끌어올린 데이터를 setData를 이용하여 새롭게 데이터를 채워준다. 그리고 새로워진 data를 자식 컴포넌트 2에 props로 내려준다.)
function App() {
const [data, setData] = useState([]);
const dataId = useRef(0);
const onCreate = (author, content, emotion) => {
const created_date = new Date().getTime();
const newItem = {
author,
content,
emotion,
created_date,
id: dataId.current,
};
dataId.current += 1;
setData([newItem, ...data]);
};
return (
<div className="App">
<DiaryEditor onCreate={onCreate} />
<DiaryList diaryList={data} />
</div>
);
}
export default App;
자식 컴포넌트 2 (spread 연산자로 흩어져서 들어왔기 때문에 아래의 형식으로 받음.)
const DiaryItem = ({author, content, created_date, emotion, id}) => {
return (
<div className="DiaryItem">
<div className="info">
<span>
작성자 : {author} | 감정점수 : {emotion}
</span>
<br />
<span className="date">
{new Date(created_date).toLocaleDateString()}
</span>
</div>
<div className="content">{content}</div>
<button
onClick={() => {
console.log(id);
}}>
삭제
</button>
</div>
);
};