React: How to inherit PropTypes?

Viewed 2930

I have a wrapper component for React Router Dom and Material UI:

import Button from '@material-ui/core/Button';
import React from 'react';
import { Link as RouterLink } from 'react-router-dom';

const forwardedLink = React.forwardRef((props, ref) => (
  <RouterLink innerRef={ref} {...props} />
));

function Link(props) {
  return (
    <Button component={forwardedLink} {...props}>
      {props.children}
    </Button>
  );
}

Link.propTypes = // ?

export default Link;

How can I give Link the Prop-Types from Button?

2 Answers

OOPS.. sorry, I didn't see at first you are trying to get the propTypes from node-module. anyhow.. if anyone needs this for inheriting propTypes in own components I leave the answer*

This works for me (using my own components) Export the props as a constant and assign it to the component.propTypes in the inherited and in the inheriting objects.

Note, first I made a mistake that I didn't see. I had forgot to use shape on all the inner objects, like this:

export const configurationPropTypes = {  
  id: PropTypes.string,
  // note: PropTypes.shape not wrapping the 'os' object
  os: {
      version: PropTypes.string,
      locale: PropTypes.string
  }
};

Above is wrong, below is correct. =)

//component being inherited 'ConfigurationListItem.js'
export const configurationPropTypes = {  
  id: PropTypes.string,
  os: PropTypes.shape({
      version: PropTypes.string,
      locale: PropTypes.string
  })
};

ConfigurationListItem.propTypes = configurationPropTypes;
//in 'QueueListItem.js', the component using ConfigurationListItem and inheriting it's propTypes

import ConfigurationListItem , {configurationPropTypes}from './ConfigurationListItem';
//...
QueueListItem.propTypes = {
  id: PropTypes.string.isRequired,
  name: PropTypes.string.isRequired,
  configurations: PropTypes.arrayOf(PropTypes.shape(configurationPropTypes))
}

See this other SO answer, the below should work.

/**
 * @type React.ForwardRefRenderFunction<React.FunctionComponent, ButtonPropTypes>
 */
const Button = forwardRef(({ text, icon }, ref) => (
  <button ref={ref}>{text}{icon}</button>
))

const ButtonPropTypes = {
  text: string.isRequired,
  icon: string.isRequired,
}

Button.propTypes = ButtonPropTypes
Related