29. Feature 및 State 로 컴포넌트 분리하기
src/components/Header.tsx
const reactDescriptions = ['Fundamental', 'Core', 'Advanced'];
function genRandomInt(max) {
return Math.floor(Math.random() * (max + 1));
}
function Header() {
const description = reactDescriptions[genRandomInt(reactDescriptions.length - 1)];
return (
<header>
<h1>{description}</h1>
</header>
);
}
export default Header;
src/components/CoreConcepts.tsx
import CoreConcepts from "./CoreConcepts";
import { CORE_CONCEPTS } from "./data";
function CoreConcepts({ title, description }) {
return (
<section id="core-concepts">
<h2>Core Concepts</h2>
<ul>
{CORE_CONCEPTS.map((concept) => (
<CoreConcepts key={concept.title} {...concept} />
))}
</ul>
</section>
);
}
export default CoreConcepts;
src/components/Examples.tsx
import { useState } from "react";
import TabButton from "./TabButton";
import { EXAMPLES } from "./data";
function Examples() {
const [selectedTopic, setSelectedTopic] = useState("components");
function handleSelect(selectedButton) {
setSelectedTopic(selectedButton);
console.log(selectedTopic);
}
let tabContent = <p>Please select a topic.</p>;
if (selectedTopic) {
tabContent = (
<div id="tab-content">
<h3>{EXAMPLES[selectedTopic].title}</h3>
<p>{EXAMPLES[selectedTopic].description}</p>
<pre>
<code>
{EXAMPLES[selectedTopic].code}
</code>
</pre>
</div>
);
}
return (
<section id="examples">
<h2>Examples</h2>
<menu>
<TabButton
isSelected={selectedTopic === 'components'}
onSelect={() => handleSelect('components')}
>
Components
</TabButton>
<TabButton
isSelected={selectedTopic === 'jsx'}
onSelect={() => handleSelect('jsx')}
>
JSX
</TabButton>
<TabButton
isSelected={selectedTopic === 'props'}
onSelect={() => handleSelect('props')}
>
Props
</TabButton>
<TabButton
isSelected={selectedTopic === 'state'}
onSelect={() => handleSelect('state')}
>
State
</TabButton>
</menu>
{tabContent}
</section>
);
}
export default Examples;
src/App.tsx
import Header from "./Header";
import CoreConcepts from "./CoreConcepts";
import Examples from "./Examples";
function App() {
return (
<div>
<Header/>
<main>
<CoreConcepts/>
<Examples/>
</main>
</div>
);
}