Three ways to create React Stateless Components in TypeScript

Thursday, 19 January 2017
TypeScript
Edit This Page

The Airbnb guidelines show three ways to implement a stateless React component using ES6 JavaScript. They make recommendations on which to use but this post is just to show the corresponding TypeScript equivalents.

In TypeScript we will define an interface for the props as:

interface ListingProps {
    hello: string;
};

Class based component:

  • JavaScript
class Listing extends React.Component {
  render() {
    return <div>{this.props.hello}</div>;
  }
}
  • TypeScript
class ListingClassComponent extends React.Component<ListingProps, object> {
    render(): JSX.Element {
        return(
            <div>{this.props.hello}</div>
        );
    }
};

Arrow Function Component

  • JavaScript
const Listing = ({ hello }) => (
  <div>{hello}</div>
);
  • TypeScript
const ListingArrowComponent: React.StatelessComponent<ListingProps> = props => 
(
    <div>{props.hello}</div>
);

Normal Function Component

  • JavaScript
function Listing({ hello }) {
  return <div>{hello}</div>;
}
  • TypeScript
function ListingFunctionComponent(props: ListingProps): JSX.Element {
    return (
        <div>{props.hello}</div>
    );
};

Simple example of all three with an event handler in props

import * as React from 'react';

export interface ButtonProps extends React.Props<HTMLDivElement> {
    text: string;
    onClick: React.EventHandler<React.MouseEvent<HTMLButtonElement>>;
};

export class ButtonClassComponent extends React.Component<ButtonProps, object> {
    render(): JSX.Element {
        const {onClick, text} = this.props;
        return(
            <div>
                <button onClick={onClick}>{text}</button>
            </div>
        );
    }
};

export function ButtonFunctionComponent(props: ButtonProps): JSX.Element {
    return (
        <div>
            <button onClick={props.onClick}>{props.text}</button>
        </div>
    );
};

export const ButtonConstComponent: React.StatelessComponent<ButtonProps> = props => 
(
    <div>
        <button onClick={props.onClick}>{props.text}</button>
    </div>
);