Rewriting Counter Component as a Function Component

ASP.NET SPA template with React-Redux is a handy one if you want to quickly spin up a SPA application. But until today, even for .NET 5, the template comes with React class components. Since I personally believe JavaScript must not have classes, I rewrote those components to React function components. Here is how I rewrote the counter component from class component to function component. Leaving it here for the purpose of helping the beginners.

File name: Counter.tsx

Class component

import * as React from 'react';
import { connect } from 'react-redux';
import { RouteComponentProps } from 'react-router';
import { ApplicationState } from '../store';
import * as CounterStore from '../store/Counter';

type CounterProps =
    CounterStore.CounterState &
    typeof CounterStore.actionCreators &
    RouteComponentProps<{}>;

class Counter extends React.PureComponent<CounterProps> {
  public render() {
    return (
      <React.Fragment>
        <h1>Counter</h1>

        <p>This is a simple example of a React component.</p>

        <p aria-live="polite">Current count: <strong>{this.props.count}</strong></p>

        <button type="button"
          className="btn btn-primary btn-lg"
          onClick={() => { this.props.increment(); }}>
          Increment
        </button>
      </React.Fragment>
    );
  }
};

export default connect(
  (state: ApplicationState) => state.counter,
  CounterStore.actionCreators
)(Counter);

Function Component

import * as React from 'react';
import { connect } from 'react-redux';
import { RouteComponentProps } from 'react-router';
import { ApplicationState } from '../store';
import * as CounterStore from '../store/Counter';

type CounterProps =
  CounterStore.CounterState &
  typeof CounterStore.actionCreators &
  RouteComponentProps<{}>;

const Counter = ({ count, increment }: CounterProps) => {
  return (
    <React.Fragment>
      <h1>Counter</h1>

      <p>This is a simple example of a React component.</p>

      <p aria-live="polite">Current count: <strong>{count}</strong></p>

      <button type="button"
        className="btn btn-primary btn-lg"
        onClick={() => { increment() }}>
        Increment
        </button>
    </React.Fragment>
    );
}

export default connect(
  (state: ApplicationState) => state.counter,
  CounterStore.actionCreators
)(Counter);

Even though React.FC is a way to define React function component, due to some limitations it was not used and discouraged to be used.

Happy Coding.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s