In React, PropTypes and Default Props are used to define the expected data types of component props and set default values for those props. This helps ensure that the correct data is passed into a component and helps avoid errors and bugs. In this article, we'll go over the basics of PropTypes and Default Props and provide an example of how to use them in a React component.
Let's start by creating a new React component called "Button" that will take in two props: "text" and "color". The "text" prop will be a string representing the text to display on the button, and the "color" prop will be a string representing the color of the button.
Here is the code for the Button component:
import React from "react";
import PropTypes from "prop-types";
const Button = ({ text, color }) => {
return (
<button style={{ backgroundColor: color }}>{text}</button>
);
};
Button.propTypes = {
text: PropTypes.string.isRequired,
color: PropTypes.string.isRequired,
};
Button.defaultProps = {
color: "blue",
};
export default Button;
In this code, we import both React and PropTypes. Then we define the Button component as a functional component that takes in the "text" and "color" props using destructuring. Inside the component, we return a button element with the text and color props applied as the button's text and background color.
Next, we define the PropTypes for the component by setting the propTypes property on the Button component. This ensures that any time the Button component is used, the "text" and "color" props are required and must be of type "string".
Finally, we set the defaultProps property on the Button component to set a default value for the "color" prop. In this case, the default value is "blue".
To replicate this example in your local machine, you can follow these steps:
- Install React and PropTypes by running the following command in your terminal:
npm install react prop-types
Create a new file called "Button.js" and copy the code above into it.
Create a new file called "App.js" and import the Button component:
import React from "react";
import Button from "./Button";
const App = () => {
return (
<div>
<Button text="Click me!" color="red" />
</div>
);
};
export default App;
- Run your application by running the following command in your terminal:
npm start
This should start your React application and display a button with the text "Click me!" and a red background color.
In conclusion, PropTypes and Default Props are important tools in React for defining the expected data types of component props and setting default values for those props. By using these tools, you can help ensure that your components are used correctly and avoid errors and bugs in your application.