DEV Community

Emmanuel Galindo
Emmanuel Galindo

Posted on

Tip for making good reusable components - React TS

When we are coding an app, most of the time we have a button or an input component in our components directory to reuse across the entire application. And what makes them reusable are their props.

One thing that I found really useful is to add at the end of destructuring the props an spread. With that I could pass different attributes for the specific html tag (button, input, etc).

const Button = ({x, y, restProps}) => {
    return <button {restProps}>btn</button>
}
Enter fullscreen mode Exit fullscreen mode

And good news are that there is someway of doing with types.

JSX.IntrinsicElements[] accepts an array of strings with the tag elements and we get the typed attributes.

type DefaultInputProps = JSX.IntrinsicElements['input'];
Enter fullscreen mode Exit fullscreen mode

Nice. And we could extend them with the props types from our component.

And in the case that we want to replace the default types of certain properties because we are going to apply ours, we just omit them with the utility type Omit.

import { ChangeEvent, RefObject } from 'react';

type DefaultInputProps = Omit<JSX.IntrinsicElements['input'],
    'name' | 'label' | 'value' | 'placeHolder'
>;

export interface InputProps extends DefaultInputProps {
    name?: string;
    label?: string;
    handleChange: (e: ChangeEvent<HTMLInputElement>) => void;
    value?: string;
    placeHolder?: string;
    ref?: ((instance: HTMLInputElement) => void) | RefObject<HTMLInputElement>
}
Enter fullscreen mode Exit fullscreen mode

Since the idea of this components is that they don’t handle their logic and state, they mostly will receive as props these properties.

Top comments (1)

Collapse
 
aalphaindia profile image
Pawan Pawar

Good one