React default props
Created By: chatGPT
In React, default props allow you to specify default values for the props that a component receives. This ensures that if a parent component does not pass a certain prop, the child component will fall back on the value defined in default props. Default props can be very useful for creating more robust components without having to check for undefined properties each time.
To set default props for a component, you can define them as a static property on the component class or object. Here’s how you can do this:
- Using class components:
class MyComponent extends React.Component {
render() {
return <div>{this.props.message}</div>;
}
}
MyComponent.defaultProps = {
message: 'Hello, World!'
};
- Using functional components with ES6 arrow function syntax:
const MyFunctionalComponent = ({ message }) => {
return <div>{message}</div>;
};
MyFunctionalComponent.defaultProps = {
message: 'Hello from Functional Component!'
};
- Using TypeScript, you can also define default props along with types:
interface MyComponentProps {
message?: string;
}
const MyComponent: React.FC<MyComponentProps> = ({ message = 'Hello from TypeScript!' }) => {
return <div>{message}</div>;
};
In the examples above, if the parent component does not provide a message
prop, the default value will be rendered instead. It is important to note that defaultProps will not work for function components without props, as the destructuring in the function signature would result in undefined
.
This technique promotes better code quality and makes components easier to use by providing clear fallbacks. Remember to always consider setting default props for optional properties that can enhance the user experience.