Skip to content

Instantly share code, notes, and snippets.

@satansdeer
Created March 18, 2020 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save satansdeer/65bb23a9f2b9561fa1be050c327ec6ea to your computer and use it in GitHub Desktop.
Save satansdeer/65bb23a9f2b9561fa1be050c327ec6ea to your computer and use it in GitHub Desktop.

Create Columns and Cards. How to Define React Components

Now that we have our styles ready we can begin working on actual components for our cards and columns.

In this section I'm not going to explain how React components work. If you need to pick this knowledge up - refer to React documentation. Make sure you know what are props, what is state and how do lifecycle events work.

Now let's see what is different when you define React components in Typescript.

How to Define Class Components? When you define a class compoenent - you need to provide types for it's props and state. You do it by using special triangle brackets syntax:

interface CounterProps {
  message: string;
};
interface CounterState {
  count: number;
};

class Counter extends React.Component<CounterProps, CounterState> {
  state: CounterState = {
    count: 0
  };

  render() {
    return (
      <div>
        {this.props.message} {this.state.count}
      </div>
    );
  }
}

React.Component is a generic type that accepts type variables for props and state. I will talk more about generics later.

You can find a working class component example in code/01-trello/class-components.

Defining Functional Components. In Typescript when you create a functional component - you don't have to provide types for it manually.

export const Example = () => {
  return <div>Functional component text</div>
}

Here we return a string wrapped into a <div/> element, so Typescript will automatically conclude that the return type of our function is JSX.Element.

If you want to be verbose - you can use React.FC or React.FunctionalComponent types.

export const Example: React.FC = () => {
  return <div>Functional component text</div>
}

Previously you could also see React.SFC or React.StatelessFunctionalComponent but after the release of hooks, it's deprecated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment