Skip to main content

Component Property Default value

This document demonstrates how assigning a default value differes by frameworks and languages

Syntax by languages

React tsx - Syntax

function AppBar({
title,
color = "white",
textColor = "red",
}: {
title: string;
color?: string;
textColor?: string;
}) {
return (
<AppBarBase color={color} textColor={textColor}>
{title}
</AppBarBase>
);
}

React jsx - Syntax

jsx requires prop-types package to be installed.

AppBar.propTypes = {
color: PropTypes.string,
textColor: PropTypes.string,
};

AppBar.defaultProps = {
color: "red",
textColor: "white",
};

References

Flutter dart - Syntax

AppBar({
Key? key,
Color color = Colors.red,
Color textColor = Colors.white,
String title,
}){
// constructor
}

References

Vue lang=js - Syntax

app.component("app-bar", {
props: {
title: {
type: String,
required: true,
},
color: {
type: String,
default: "red",
},
textColor: {
type: String,
default: "white",
},
},
});

References

A Universal redundant way

Or we can optionally use a falsy gate to assign default property inside a body (example based on ts)

interface AppBarProps {
color: string;
}

const color = p.color ?? "red";