How to use Default Props in React with TypeScript

Adding default props to a stateful component in React with TypeScript has been a pain. TypeScript 3 is making this process as simple as:

  1. Get rid of the optional ? operator on your props

  2. Add a static defaultProps object at the top of your component and you're done

Here's a simple example with a component that has a prop to change the color.

import * as React from "react"

type CardColors = "red" | "blue"

export interface ColorCardProps {
    color: CardColors
    // Don't use the optional parameter below
    // color?: CardColors
}

export interface ColorCardState {
    color: CardColors
}

export default class ColorCard extends React.Component<ColorCardProps, ColorCardState> {
    static defaultProps = {
        color: "red"
    }

    state = {
        color: this.props.color
    }

    flipColor = () => {
        this.setState((prevState, props) => {
            return {
                color: prevState.color === "red" ? "blue" : "red"
            }
        })
    }

    render() {
        return (
            <div
                style={{
                    backgroundColor: this.state.color,
                    height: 300,
                    width: 300
                }}
                onClick={this.flipColor}
            >
                {this.props.children}
            </div>
        )
    }
}

Stateless functional components are still as easy as ever thanks to default parameters.

export interface UserProps {
    name: string
}


function User({ name = "Jane Doe" }: UserProps) {
    return <span>Hello ${name.toUpperCase()}!</span>;
}

One Last Thing...

If you have a question or see a mistake, please comment below.

If you found this post helpful, please share it with others. It's the best thanks I can ask for & it gives me momentum to keep writing!

Matt Ferderer
Software Developer focused on making great user experiences. I enjoy learning, sharing & helping others make amazing things.
Let's Connect