Reputation: 49230
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"
/>
Upvotes: 6
Views: 17234
Reputation: 1562
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
// ...
}
Upvotes: 6
Reputation: 13933
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
}
Upvotes: 10