47

Typescript. Simple React components.

 4 years ago
source link: https://www.tuicool.com/articles/Ibq2MrM
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Hello there. I very like to use React and Typescript. Almost in each new project need simple components, like atoms, for example: button, input, checkbox etc. I have some best practices to make it friendly for all members of team, but also with strict typings. Let's get a look, maybe it will be helpful for you too.

Button

import React from 'react';

interface IProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  block?: true; // Your some custom prop
}

export const Button: React.FunctionComonent<IProps> = ({ block, children, ...shared }) => {
  return <button {...shared}>{children}</button>;
}

Button.defaultProps = {
  type: 'button',
}

That's it. You have custom Button component, that supports all native button attributes with strict typings. You can put common things for all buttons in project, like styles or some business logic.

For use

import React from 'react'

instead of

import * as React from 'react'

add in your tsconfig.json property esModuleInterop: true

Input

import React from 'react';

interface IProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'onChange' | 'value'> {
  value: string;

  onChange(value: string): void;
}

export const Input: React.FunctionComponent<IProps> = ({ children, onChange, ...shared }) => {
  return <input onChange={e => onChange(e.target.value)} {...shared} />;
}

Input.defaultProps = {
  type: 'text',
};

The Omit helper type was added in Typescript 3.5. If you use previous version of Typescript, just add this string:

type Omit<T, K> = Pick<T, Exclude<keyof T, K>>

Checkbox

import React from 'react';

interface IProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'onChange'> {
  onChange(value: boolean): void;
}

export const Checkbox: React.FunctionComponent<IProps> = ({ children, 
onChange, ...shared }) => {
  return <input onChange={e => onChange(e.target.checked)} {...shared} />
}

Checkbox.defaultProps = {
  type: 'checkbox',  
}

Now you can use it like here:

<Checkbox checked={false} onChange={toggleCheckbox} />

It is end of small tutorial. If it will be helpful for someone, I can continue to explain some good things of React and Typescript. Thanks for attention.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK