One of the core principles in designing reusable components is to break them down into smaller, single-purpose parts. By doing this, we create components that can serve as building blocks for more complex parts of the application. A good rule of thumb: if a component is doing too many things or feels bulky, consider splitting it up.
Example: A Reusable Button Component
Let’s start with a simple example: a Button component. Instead of creating several different buttons with hardcoded styles throughout the app, we can create one flexible Button component. This button can accept props that allow for different styles or functionalities wherever it’s used.
// Button.js
import React from 'react';
// Button component with configurable style and behavior
const Button = ({ onClick, children, styleType = 'primary' }) => {
const styles = {
primary: 'bg-blue-500 text-white',
secondary: 'bg-gray-500 text-black',
};
return (
<button onClick={onClick} className={`px-4 py-2 ${styles[styleType]}`}>
{children}
</button>
);
};
export default Button;
Now, the Button component can be used throughout your app with consistent styling and behavior.