Creating the Die Component
In this section, you will create the Die component in its own file and compose it into the app.
Importing, Exporting, and Composing Components
In the Counter app, all of your UI was inside App. Most apps are built from many components, so let’s create a separate one.
Create a new file src/components/Die.tsx:
function Die() {
return <button>🎲</button>;
}
export default Die;
Now update src/App.tsx to use it:
import Die from "./components/Die";
function App() {
return (
<div className="flex min-h-screen flex-col items-center justify-center gap-8 bg-green-700">
<h1 className="text-4xl font-bold text-white">Dice Roller</h1>
<Die />
</div>
);
}
export default App;
A few things to notice:
- We
exportthe component from its file andimportit where we need it, just like any other JavaScript module. - We use it like an HTML tag:
<Die />, notDie(). React components are always rendered as JSX elements, never called as functions directly. Appis now composed of other components.Appcontains aDie, just like a<div>can contain a<button>. This is the component model: you build complex UIs by combining smaller components.
Checkpoint: Commit your progress.
git add .
git commit -m "dice-03: Build the Die component"
git push