Build Your First Interactive React Component with TypeScript: A Step-by-Step Guide
Learn to build a practical, interactive React component using TypeScript, following a step-by-step tutorial for improved code quality and maintainability.
React has transformed how we build user interfaces, and TypeScript takes that power further by adding robustness and clarity. If you're ready to move beyond basic JavaScript in your React projects and build components that are not only interactive but also maintainable and error-resistant, you're in the right place. This guide will walk you through building your first interactive React component using TypeScript, step by step.
Why TypeScript for React?
Adding TypeScript might seem like an extra step, but its benefits quickly outweigh the initial learning curve. TypeScript brings static typing to JavaScript, catching errors at development time rather than runtime. For React components, this means:
- Predictable Props: Clearly define the types of props your components expect.
- Enhanced Readability: Code becomes self-documenting, improving collaboration.
- Improved Developer Experience: IDEs provide better autocompletion, type checking, and refactoring tools.
- Maintainability: As projects scale, TypeScript helps prevent regressions and makes refactoring safer. These practices are key to strong Software Engineering Craft.
Our Project: A Theme Switcher Component
To illustrate these benefits, we’ll build a ThemeSwitcher component. This simple, interactive element will allow users to toggle between "light" and "dark" themes, demonstrating state management, prop types, and basic styling within a TypeScript React environment.
Prerequisites
Before we begin, ensure you have Node.js and npm/yarn installed, and a basic understanding of React fundamentals. If you're new to coding, exploring resources like Which Programming Language Should You Learn First? can provide a solid foundation.
Step 1: Set Up Your React with TypeScript Project
First, create a new React project configured with TypeScript. Open your terminal and run:
``bash npx create-react-app my-theme-switcher --template typescript cd my-theme-switcher ``
This command uses Create React App to scaffold a new project, including all necessary TypeScript configurations automatically.
Step 2: Define Component Props with TypeScript Interfaces
Inside your src folder, create a new file named ThemeSwitcher.tsx. We'll start by defining the types for the props our component will accept using a TypeScript interface.
```typescript // src/ThemeSwitcher.tsx import React, { useState } from 'react';
// Define the interface for our component's props interface ThemeSwitcherProps { initialTheme?: 'light' | 'dark'; // Optional prop, defaults to 'light' onThemeChange?: (theme: 'light' | 'dark') => void; // Optional callback }
// Our functional component, typed with React.FC and our props interface const ThemeSwitcher: React.FC<ThemeSwitcherProps> = ({ initialTheme = 'light', // Default value if not provided onThemeChange, }) => { // Component logic will go here return ( <div> {/ Content will go here /} </div> ); };
export default ThemeSwitcher; ```
Here, ThemeSwitcherProps explicitly states the shape of the props. initialTheme is an optional union type ('light' | 'dark'), and onThemeChange is an optional function type. This provides immediate type checking as you use the component.
Step 3: Implement Component Logic and State
Now, let's add the interactive logic. We'll use React's useState hook, explicitly typed, to manage the current theme state and a button to toggle it.
```typescript // src/ThemeSwitcher.tsx (continued) // ... (imports and interface definition as above)
const ThemeSwitcher: React.FC<ThemeSwitcherProps> = ({ initialTheme = 'light', onThemeChange, }) => { // Use useState to manage the current theme, explicitly typing its state const [currentTheme, setCurrentTheme] = useState<'light' | 'dark'>(initialTheme);
const toggleTheme = () => { const newTheme = currentTheme === 'light' ? 'dark' : 'light'; setCurrentTheme(newTheme); onThemeChange?.(newTheme); // Invoke callback if provided };
return ( <div className={theme-switcher ${currentTheme}}> <p>Current Theme: <strong>{currentTheme}</strong></p> <button onClick={toggleTheme}>Toggle Theme</button> {/ Basic inline style for quick visual feedback /} <style>{ .theme-switcher.light { background-color: #f0f0f0; color: #333; padding: 15px; border-radius: 8px; border: 1px solid #ddd; margin-bottom: 20px;} .theme-switcher.dark { background-color: #333; color: #f0f0f0; padding: 15px; border-radius: 8px; border: 1px solid #555; margin-bottom: 20px;} .theme-switcher button { padding: 10px 15px; cursor: pointer; border: none; border-radius: 5px; background-color: #007bff; color: white; font-size: 16px; margin-left: 15px; transition: background-color 0.2s ease; } .theme-switcher button:hover { background-color: #0056b3; } }</style> </div> ); };
export default ThemeSwitcher; ```
Explicitly typing useState as useState<'light' | 'dark'>(initialTheme) ensures currentTheme can only hold one of those two string literal values, preventing unexpected states.
Step 4: Integrate Your Component into App.tsx
Finally, let's use our ThemeSwitcher component in App.tsx.
```typescript // src/App.tsx import React from 'react'; import ThemeSwitcher from './ThemeSwitcher'; // Import our component import './App.css'; // Global styles for theme
function App() { const handleThemeChange = (newTheme: 'light' | 'dark') => { console.log('Theme changed to:', newTheme); document.body.className = newTheme === 'dark' ? 'dark-theme' : 'light-theme'; };
return ( <div className="App"> <header className="App-header"> <h1>Welcome to Your Theme-Enabled React App</h1> <p>This is a demonstration of an interactive React component with TypeScript.</p> </header> <main> <section> <h2>Theme Control</h2> <ThemeSwitcher onThemeChange={handleThemeChange} initialTheme="dark" /> <p>You can see the theme switch above, demonstrating type-safe interactivity.</p> </section> <section> <h2>Expanding Your Skills</h2> <p> Building robust web applications often involves more than just frontend. Many learners on Tully explore broader areas like Full-Stack Web Development with Node.js and Express, combining their frontend skills with backend services. You can also explore the entire <a href="https://tullycourses.com/learn/web-development">web development topic hub</a>. </p> </section> </main> </div> ); }
export default App; `` For App.css, add these basic styles to observe the theme change: ``css / src/App.css / body.light-theme { background-color: #ffffff; color: #333; }
body.dark-theme { background-color: #282c34; color: #f0f0f0; }
.App-header { padding: 20px; text-align: center; background-color: #61dafb; / Default light / color: white; } .dark-theme .App-header { background-color: #444; color: white; } / General App styles, not directly theme related but for presentation / .App { font-family: Arial, sans-serif; min-height: 100vh; } .App-header h1 { margin-bottom: 5px; } .App-header p { margin-top: 5px; } main { padding: 20px; max-width: 600px; margin: 0 auto; } main section { margin-top: 30px; border-top: 1px solid #eee; padding-top: 20px; } main section:first-of-type { margin-top: 0; border-top: none; padding-top: 0; } `` Run your application with npm start (or yarn start), and you’ll see your interactive ThemeSwitcher` in action, robustly typed by TypeScript.
Conclusion
You've successfully built an interactive React component using TypeScript! You leveraged interfaces for prop typing, used useState with explicit types for robust state management, and integrated the component. This foundation allows you to create more reliable, maintainable, and scalable React applications.
Web development is a trending topic on Tully, with 3 related courses. If you're looking to deepen your skills, whether in frontend, backend, or full-stack, Tully offers 47 public courses, with programming being a popular domain, boasting 23 courses.
Ready to Build More?
Practical, project-based learning is at the heart of Tully. Build confidence by doing, get honest feedback, and follow a path that adapts to your progress.
Start learning with Tully today!
Start learning on Tully Courses — learn anything by doing it.