const MyContext = React.createContext(defaultValue);
<MyContext.Provider value={ }>
<AComponent />
<BComponent />
<CComponent />
</MyContext.Provider>
[참고] 변경 사항은
Object.is
와 동일한 알고리즘을 사용하여 이전 값과 비교하여 결정됨.
const value = useContext(MyContext);
사용 예시
const themes = {
light: {
foreground: "#000000",
background: "#eeeeee"
},
dark: {
foreground: "#ffffff",
background: "#222222"
}
};
const ThemeContext = React.createContext(themes.light); // initialState 지정하여 생성
const App = () => {
return (
<ThemeContext.Provider value={themes.dark}>
<Toolbar />
</ThemeContext.Provider>
);
}
const Toolbar = () => {
return (
<div>
<ThemedButton/>
</div>
);
}
const ThemedButton = () => {
const theme = useContext(ThemeContext); // themes.dark
return (
<button style={{background: theme.background, color: theme.foreground}}>
style button
</button>)
}
themes.light
지만,themes.dark
이므로themes.dark
가 됨.$ npx create-react-app ./
/src/pages에 아래와 같이 각 페이지 폴더와 index.js 생성
const SummaryPage = () => {
return <div>SummaryPage</div>;
};
export default SummaryPage;
구현해야 할 기능
- 주문 확인 체크박스 체크해야 [주문 확인] 버튼 클릭 가능.
- form을 이용하여 구현 (input checkbox)
checked
state를 관리import { useState } from 'react';
const SummaryPage = () => {
const [checked, setChecked] = useState(false);
return (
<div>
<form>
<input
type="checkbox"
checked={checked}
onClick={(e) => setChecked(e.target.checked)}
id="confirm-checkbox"
/>{' '}
<label htmlFor="confirm-checkbox">주문하려는 것을 확인하셨나요?</label>
<br />
<button disabled={!checked} type="submit">
주문 확인
</button>
</form>
</div>
);
};
export default SummaryPage;
App > OrderPage > Type
OrderType
이라는 props를 받아서 구분함const Type = ({ orderType }) => {
return (
<>
<h2>주문 종류</h2>
<p> 하나의 가격</p>
<p>총 가격:</p>
<div
style={{
display: 'flex',
flexDirection: orderType === 'options' && 'column',
}}
></div>
</>
);
};
export default Type;
const OrderPage = () => {
return (
<div>
<h1>Travel Products</h1>
<div>
<Type orderType="products" />
</div>
<div style={{ display: 'flex', marginTop: 20 }}>
<div style={{ width: '50%' }}>
<Type orderType="options" />
</div>
<div style={{ width: '50%' }}>
<h2>Total Price</h2> <br />
<button>주문</button>
</div>
</div>
</div>
);
};
export default OrderPage;
import { useEffect, useState } from 'react';
import axios from 'axios';
import Products from './Products';
import Options from './Options';
const Type = ({ orderType }) => {
const [items, setItems] = useState([]);
console.log(orderType);
useEffect(() => {
loadItems(orderType);
}, [orderType]);
const loadItems = async (orderType) => {
try {
const response = await axios.get(`http://localhost:4000/${orderType}`);
setItems(response.data);
} catch (error) {
console.error(error);
}
};
const ItemComponents = orderType === 'products' ? Products : Options;
const optionItems = items.map((item) => (
<ItemComponents
key={item.name}
name={item.name}
imagePath={item.imagePath}
/>
));
return <>{optionItems}</>;
};
export default Type;
const Products = ({ name, imagePath }) => {
console.log('products : ', name, imagePath);
return <>Products</>;
};
export default Products;
const Products = ({ name, imagePath }) => {
console.log('products : ', name, imagePath);
return (
<div style={{ textAlign: 'center' }}>
<img
src={`http://localhost:4000/${imagePath}`}
alt={`${name} product`}
style={{ width: '75%' }}
/>
</div>
);
};
export default Products;
const ErrorBanner = ({ message }) => {
let errorMessage = message || '에러입니다.';
return <div style={{ backgroundColor: 'red' }}>{errorMessage}</div>;
};
export default ErrorBanner;
import { useEffect, useState } from 'react';
import axios from 'axios';
import Products from './Products';
import Options from './Options';
import Error from './Error';
const Type = ({ orderType }) => {
const [items, setItems] = useState([]);
const [error, setError] = useState(false);
useEffect(() => {
loadItems(orderType);
}, [orderType]);
const loadItems = async (orderType) => {
try {
const response = await axios.get(`http://localhost:4000/${orderType}`);
setItems(response.data);
} catch (error) {
setError(true); // 에러 처리
}
};
const ItemComponents = orderType === 'products' ? Products : Options;
const optionItems = items.map((item) => (
<ItemComponents
key={item.name}
name={item.name}
imagePath={item.imagePath}
/>
));
return (
<>
{optionItems}
{error && <Error />}
</>
);
};
export default Type;