Câu hỏi phỏng vấn Reactjs
Câu hỏi

How to apply validatio...

Câu trả lời

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:

Step 1: Install the prop-types Library

First, 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

Step 2: Import PropTypes

In your component file, import the PropTypes from the prop-types package:

import PropTypes from 'prop-types';

Step 3: Define PropTypes for the Component

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;

Step 4: Set Default Props

Optionally, you can define default values for your props using defaultProps:

UserProfile.defaultProps = {
    name: 'Anonymous'
};

Additional Validation Techniques

  • Custom Validators: For more complex validations, you can write custom validator functions. For example, validating that a number is within a range:
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.`);
        }
    }
};
  • **Using `is...
senior

senior

Gợi ý câu hỏi phỏng vấn

middle

How to bind methods or event handlers in JSX callbacks?

senior

What's a Pure Functional Component in React?

expert

What is the key architectural difference between a JavaScript library such as React and a JavaScript
framework such as Angular?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào