How to apply validatio...
How to apply validatio...
To apply validation on props in ReactJS, you can use the prop-types
library, which allows you to specify the data types of props that a component should receive. This helps in catching bugs and errors by ensuring that components receive the right type of data. Here’s a step-by-step guide on how to apply validation on props using prop-types
:
prop-types
LibraryFirst, you need to add the prop-types
library to your project. You can install it using npm or yarn:
npm install prop-types --save
or
yarn add prop-types
PropTypes
In your component file, import the PropTypes
from the prop-types
package:
import PropTypes from 'prop-types';
After importing PropTypes
, you can define the expected prop types for your component. Here’s an example of a component that expects a string prop name
, a required number prop age
, and an optional function onClick
:
import React from 'react';
import PropTypes from 'prop-types';
const UserProfile = ({ name, age, onClick }) => {
return (
<div>
<h1>{name}</h1>
<p>Age: {age}</p>
<button onClick={onClick}>Click Me</button>
</div>
);
};
UserProfile.propTypes = {
name: PropTypes.string,
age: PropTypes.number.isRequired,
onClick: PropTypes.func
};
export default UserProfile;
Optionally, you can define default values for your props using defaultProps
:
UserProfile.defaultProps = {
name: 'Anonymous'
};
UserProfile.propTypes = {
age: function(props, propName, componentName) {
if (props[propName] < 0 || props[propName] > 100) {
return new Error(`${propName} in ${componentName} must be between 0 and 100.`);
}
}
};
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào