Build Button Component in React

Friday, March 5, 20212 min read

When it comes to creating a Button component in React, there are various approaches you can take. Personally, I prefer to create my components using TypeScript as it offers the advantage of making the code more self-descriptive.

Many developers create a Button component in the following way:

1type Props = {
2 size: 'sm' | 'md' | 'lg';
3 children: string;
4};
5
6function Button({
7 size,
8 children
9}: Props): JSX.Element => (
10 ...
11)
12
13export default Button;

Firstly there is not only a correct way to build a component.

While there isn't a single correct way to build a component, this approach has some limitations. One limitation is that it doesn't allow the use of native attributes like onClick, type, or role...

Another limitation is the use of the string type for the children prop, which restricts the button to only accepting plain text. It doesn't provide the flexibility to include other components or icons inside the button.

To address these limitations, let's make some improvements:

1export interface ButtonProps
2 extends React.ButtonHTMLAttributes<HTMLButtonElement> {
3 size: 'sm' | 'md' | 'lg';
4}
5
6export const Button = ({
7 size = 'md',
8 type = 'button',
9 children,
10 ...resetProps
11}: ButtonProps): React.ReactElement => (
12 <button {...resetProps} type={type}>
13 {children}
14 </button>
15);

Use our Button component

1import { Button } from './button';
2
3export const App = () => {
4 return (
5 <>
6 <Button size="sm" onClick={() => console.log('Click Me!')}>
7 Small Button
8 </Button>
9 <Button size="lg" type="submit" disabled>
10 Small Large
11 </Button>
12 </>
13 );
14};

In this improved version, our Button component allows the use of all the attributes of the native <button> element. Additionally, it enables us to use not only plain text but also other components or icons inside the button.

By leveraging TypeScript's type intersection and the ButtonHTMLAttributes type, we can easily extend the functionality of our Button component while maintaining compatibility with native attributes.

These improvements provide a more robust and flexible Button component that can better accommodate different use cases and allow for easier customization.


Thursday, June 27, 2024

Introduction of the useBem hook for React

Discover the power of the useBem hook to streamline your CSS class management, learn how to apply the BEM methodology to ensure consistent, readable, and maintainable styling across your front-end projects.


Wednesday, October 4, 2023

SOLID Principles in React

Let's explore how the SOLID principles can be applied to React components using TypeScript, functions, hooks, and interfaces.