2-how-to-create-reusable-components-in-react-with-typescript.html

How to Create Reusable Components in React with TypeScript

In the world of modern web development, efficiency and maintainability are paramount. React, a popular JavaScript library for building user interfaces, allows developers to create reusable components, which are essential for building scalable applications. When combined with TypeScript—a superset of JavaScript that adds static typing—developers can enhance their code's reliability and clarity. In this guide, we will explore how to create reusable components in React using TypeScript, complete with practical examples and actionable insights.

What are Reusable Components?

Reusable components are self-contained building blocks of a user interface that can be utilized across multiple parts of an application. They encapsulate logic, styles, and behavior, making them easy to maintain and test. By creating reusable components, developers can:

  • Save Time: Write once, use multiple times.
  • Maintain Consistency: Ensure a uniform look and feel across the application.
  • Enhance Collaboration: Allow teams to work independently on different components.

Why Use TypeScript with React?

TypeScript provides powerful features that help in building robust applications, including:

  • Static Typing: Catch errors at compile time rather than runtime.
  • Enhanced IDE Support: Better autocompletion and documentation within IDEs.
  • Improved Readability: Clearer code structure, especially in large applications.

Setting Up Your React and TypeScript Environment

Before we dive into creating reusable components, let’s set up a new React application with TypeScript. Open your terminal and run the following command:

npx create-react-app my-app --template typescript

Change into the project directory:

cd my-app

Now, you’re ready to start developing components!

Creating a Reusable Button Component

Let’s create a simple reusable button component that accepts props for customization. This button will be styled and can have various functionalities.

Step 1: Define the Button Component

Create a new file called Button.tsx in the src/components directory:

// src/components/Button.tsx

import React from 'react';

interface ButtonProps {
  label: string;
  onClick: () => void;
  variant?: 'primary' | 'secondary';
}

const Button: React.FC<ButtonProps> = ({ label, onClick, variant = 'primary' }) => {
  const buttonStyle = variant === 'primary' 
    ? { backgroundColor: 'blue', color: 'white' } 
    : { backgroundColor: 'gray', color: 'black' };

  return (
    <button style={buttonStyle} onClick={onClick}>
      {label}
    </button>
  );
};

export default Button;

Step 2: Use the Button Component

Now that we have our button component, let’s use it in the App.tsx file:

// src/App.tsx

import React from 'react';
import Button from './components/Button';

const App: React.FC = () => {
  const handlePrimaryClick = () => {
    alert('Primary Button Clicked!');
  };

  const handleSecondaryClick = () => {
    alert('Secondary Button Clicked!');
  };

  return (
    <div>
      <h1>Reusable Button Component</h1>
      <Button label="Primary Button" onClick={handlePrimaryClick} />
      <Button label="Secondary Button" onClick={handleSecondaryClick} variant="secondary" />
    </div>
  );
};

export default App;

Key Features of the Button Component

  1. Props: The component accepts label, onClick, and an optional variant prop. This allows for customization.
  2. Styling: Inline styles are used based on the variant, but you can also use CSS modules or styled-components for more complex styles.
  3. Type Safety: TypeScript ensures that the correct types are passed to the component, reducing runtime errors.

Creating a Reusable Input Component

Next, let’s create a reusable input component that can handle different types of inputs, such as text and passwords.

Step 1: Define the Input Component

Create a new file called Input.tsx in the src/components directory:

// src/components/Input.tsx

import React from 'react';

interface InputProps {
  type?: 'text' | 'password';
  placeholder: string;
  value: string;
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
}

const Input: React.FC<InputProps> = ({ type = 'text', placeholder, value, onChange }) => {
  return (
    <input
      type={type}
      placeholder={placeholder}
      value={value}
      onChange={onChange}
      style={{ padding: '10px', margin: '5px', border: '1px solid #ccc' }}
    />
  );
};

export default Input;

Step 2: Use the Input Component

Update your App.tsx to include the input component:

// src/App.tsx

import React, { useState } from 'react';
import Button from './components/Button';
import Input from './components/Input';

const App: React.FC = () => {
  const [text, setText] = useState('');

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setText(e.target.value);
  };

  return (
    <div>
      <h1>Reusable Input Component</h1>
      <Input type="text" placeholder="Enter text" value={text} onChange={handleInputChange} />
      <Button label="Submit" onClick={() => alert(`Submitted: ${text}`)} />
    </div>
  );
};

export default App;

Conclusion

Creating reusable components in React using TypeScript enhances your application’s scalability, maintainability, and efficiency. By following the steps outlined in this article, you've learned how to build two reusable components—a button and an input field—demonstrating the power of TypeScript for type safety and clarity.

Key Takeaways

  • Reusable Components: Break down your UI into manageable pieces that can be reused throughout your application.
  • Type Safety: TypeScript helps catch potential errors early in the development process.
  • Customization: Leverage props to make your components versatile and adaptable to various use cases.

By implementing these practices, you can create a robust, maintainable codebase that will serve you well in the long run. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.