Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react prop-types: reusable validator from existing prop-types

When it comes to using prop-types in React, is there a way to create reusable validators from existing validators


Example: validating a "header" object where a header has a title and an icon:

Component.propTypes = {
  header: PropTypes.shape({
    title: PropTypes.string.isRequired,
    icon: PropTypes.element,
  })
}

instead of repeating this as the prop gets passed down a chain of components, can we write a reusable isHeader function

Component.propTypes = {
  header: isHeader
}
like image 614
Thierry Prost Avatar asked Dec 19 '25 03:12

Thierry Prost


1 Answers

You should be able to create your reusable type like this:

const myReusableHeader = PropTypes.shape({
  title: PropTypes.string.isRequired,
  icon: PropTypes.element,
})

And then you can use it in your components like this:

Component.propTypes = {
  header: myReusableHeader
}
like image 188
David Callanan Avatar answered Dec 21 '25 18:12

David Callanan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!