How to set default value of props if not passed to functional component in NextJS using Typescript

Viewed 4767

This is the component:

const defaultDesc = "welcome to homepage";

    export default function Header(Props: {
       title:string,
      desc?:string
    }): JSX.Element {
    
    }

If I don't pass desc in <Header> then I'd like to set defaultDesc value by default. One way to that is to check for empty value of desc and then set it to defaultDesc.
But, is there any other efficient way which avoids multiple checks in case passing many props.

      <Header
        title="Homepage"
      />
2 Answers

You can define an interface and destructure the Props with the default value in case Props don't have optional argument passed to the Component as

const defaultDesc = "welcome to homepage";

interface  HeaderProps{
       title:string,
      desc?:string
}

export default function Header(Props: HeaderProps): JSX.Element {
    
const { title, desc= defaultDesc } = Props;   // you can use let, however const is recommended


}

Reference

Whenever I am passing two (min 1 variable with default value) or more parameters to the function as argument I create interface/type for them to be more readable.

In this case, I would have done something like this.

const defaultDesc = "welcome to homepage";

interface Props {
    title: string,
    desc?: string,
}

export default function Header({
    title,
    desc=defaultDesc // this is what you are looking for
}: Props): JSX.Element {

    // rest of the logic
    // ...
}
Related