Props Validation in React JS is a process of checking whether the data being passed to components as props meet certain criteria. This validation can be done either statically (at compile time) or dynamically (at runtime). Static prop validation is performed using Prop Types, which are specified as properties on components and ensure that only valid values are accepted before compilation. On the other hand, dynamic prop validation occurs when a component receives new props from its parent at runtime and checks them against certain rules defined by the developer.
Either way, proper prop validation helps prevent errors by ensuring that invalid data does not end up affecting the application state or functionality.
Here is an example of a component that uses prop-types to validate its props:
import React from 'react';
import PropTypes from 'prop-types';
function MyComponent(props) {
return <h1>Hello, {props.name}!</h1>;
}
MyComponent.propTypes = {
name: PropTypes.string.isRequired
};
export default MyComponent;
In this example, the component is using the propTypes property to define the types and validation rules for the name prop. The name prop is defined as a string and is marked as required using the is required method.
You can also specify the type of a prop using one of the following:
● PropTypes.string
● PropTypes.number
● PropTypes.bool
● PropTypes.object
● PropTypes.array
● PropTypes.func
● PropTypes.symbol
You can also use PropTypes.oneOf to specify a set of valid values for a prop.
MyComponent.propTypes = {
size: PropTypes.oneOf(['small', 'medium', 'large']).isRequired
};
You can also use PropTypes.shape to specify the shape of an object prop.
MyComponent.propTypes = {
user: PropTypes.shape({
name: PropTypes.string.isRequired,
age: PropTypes.number
}).isRequired
};
It's important to note that props validation is a development-only feature and it is stripped from the production build.