Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to handle prop-types for a component that uses object destructing and object rest...spread to collect props

I have a component like so:

import React from 'react'
import { bool } from 'prop-types'

const Component = ({ active, ...rest}) => (
  // ...does things
)

Component.propTypes = {
  active: bool.isRequired,
  // -> how do i handle { ...rest } here?
  rest: object // ? works, but is it the right solution?
}

Component destructures its props, grabbing the active prop and collecting the "rest" into rest. Is there a way to validate rest using prop-types? Is it required? Not sure what to do.

like image 956
jakewies Avatar asked Oct 16 '25 11:10

jakewies


2 Answers

https://www.ian-thomas.net/custom-proptype-validation-with-react/

Basically, prop-types does allow custom validation. You set it to

Component.propTypes = {
  rest: function(props, propName, componentName) { // return null if all is well }
}
like image 86
TKoL Avatar answered Oct 19 '25 01:10

TKoL


Although it's late, here I'm leaving a snippet of how I do things in case I want to extend a library or same concept can be utilized when building own component

(This is in case you don't want to use typescript and stay with plain old javascript)

import React from "react";
import PropTypes from "prop-types";
import { Button } from "reactstrap";

let BtnBaseProps = Object.assign(
  {
    leftIcon: "",
    rightIcon: "",
  },
  Button.prototype.props
);

/**
 *
 * @param {BtnBaseProps} props
 * @returns
 */
const BtnBase = (props) => {
  return (
    <Button {...props}>
      {props.leftIcon ? <i className={sicon + " mr-2"} /> : null}
      {props.children}
      {props.rightIcon ? <i className={eicon + " ml-2"} /> : null}
    </Button>
  );
};

BtnBase.propTypes = {
  leftIcon: PropTypes.string,
  rightIcon: PropTypes.string,
  ...(Button.propTypes && Button.propTypes),
};

export default BtnBase;

like image 23
Md.Reyad Hossain Avatar answered Oct 19 '25 01:10

Md.Reyad Hossain



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!