You get a bonus - 1 coin for daily activity. Now you have 1 coin

How do you validate props in React? in REACT

Practice



  1. When the application runs in development mode , React will automatically check all the props we set on components to make sure they have the correct type . If the type is wrong, React will generate warning messages in the console. It is disabled in production mode because of the performance impact. Required props are declared with

    isRequired
    .

    The set of predefined prop types:

    1. PropTypes.number
    2. PropTypes.string
    3. PropTypes.array
    4. PropTypes.object
    5. PropTypes.func
    6. PropTypes.node
    7. PropTypes.element
    8. PropTypes.bool
    9. PropTypes.symbol
    10. PropTypes.any

    We can define

    propTypes
    for the
    User
    component as shown below:
    import React from 'react'
    import PropTypes from 'prop-types'
    
    class User extends React.Component {
      static propTypes = {
        name: PropTypes.string.isRequired,
        age: PropTypes.number.isRequired
      }
    
      render() {
        return (
          <>
            <h1>{`Welcome, ${this.props.name}`}</h1>
            <h2>{`Age, ${this.props.age}`}</h2>
          </>
        )
      }
    }

    Note: In React v15.5 PropTypes were moved out of

    React.PropTypes
    into the
    prop-types
    library.

⬆ Back to top

created: 2020-02-23
updated: 2026-03-08
238



Was this answer useful?
Choose a quick rating so we can improve the next answer for you.
How satisfied are you?


Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Scripting client side JavaScript, jqvery, BackBone"

Terms: Scripting client side JavaScript, jqvery, BackBone