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>;
}

Matt Ferderer

Full Stack Software Developer focused on JavaScript and C#. Love to share & help others make amazing things. Have a project you need help on? Let's talk!

comment

Comments