简体   繁体   中英

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

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"
      />

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
    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM