Creating Default props
Default props in React allow you to set fallback values for component properties. This ensures your component has a value to use even if no prop is passed, this helps in preventing unwanted errors.
Default props can be intialized by following the below syntax.
componentName.defaultProps = {
propName : value
};
Example : This example exhibit’s the use of Default props and focuses on preventing errors with defaults.
function MyComponent({name}) {
return (
<div>
{name}
</div>
)
}
MyComponent.defaultProps = {
name: 'Default'
};
export default MyComponent;
Output:
How to use PropTypes for Type-Checking in React Components ?
React is a JavaScript library for building user interfaces, and one of its key features is component-based architecture. When building React components, it’s essential to ensure that the data passed to them is of the correct type. PropTypes is a built-in type-checking library in React that helps developers validate the props passed to components during development.