📝 팬레터함 만들기 ②
✅ context 만들기
- src/context/FanLetterContext.js 생성
import { createContext } from 'react';
export const FanLetterContext = createContext();
✅ context 적용
- 사용할 컴포넌트 감싸기 (shared/Router.js)
- value 넣어주기 (Context에 넣을 데이터)
const Router = () => {
const [fanLetters, setFanLetters] = useState(FakeData);
const [selectedMember, setSelectedMember] = useState('전체');
return (
<BrowserRouter>
<Header />
<FanLetterContext.Provider
value={{ fanLetters, setFanLetters, selectedMember, setSelectedMember }}
>
<Routes>
<Route path='/' element={<Home />} />
<Route path='details/:id' element={<Details />} />
<Route />
</Routes>
</FanLetterContext.Provider>
</BrowserRouter>
);
};
✅ useContext 사용
- useContext, FanLetterContext import
useContext()
로 가져와서 사용하기
import React, { useContext } from 'react';
import { FanLetterContext } from 'context/FanLetterContext';
const FanLetterList = () => {
const { fanLetters, selectedMember } = useContext(FanLetterContext);
(...)
};
export default FanLetterList;