Validating Data types
To validate whether a received prop is a string or not using PropTypes, you can use the PropTypes.string
validator. This ensures that the prop passed to the component is of type string, providing a simple and effective way to validate data types.
Example : Implementation to showcase the validation of data types using PropTypes.
// App.js
import MyComponent from './myComponent';
function App() {
return (
<div>
<MyComponent name={1} />
</div>
);
}
export default App;
// myComponent.js
import PropTypes from 'prop-types'
function MyComponent({ name }) {
return (
<div>
{name}
</div>
)
}
MyComponent.propTypes = {
name: PropTypes.string
}
export default MyComponent
Step to Run Application: Run the application using the following command from the root directory of the project
npm start
Output: Your project will be shown in the URL http://localhost:3000/
Explanation: In the above example given, the component “MyComponent” has received a prop of type “number”. Although a component can receive props of any type, a warning is being displayed in the console because a rule has been declared (i.e., name: PropTypes.string) that specifies that the received props should be of type “string”.
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.