3

I want to centralize proptypes that might contain different properties and be or not required. As an example:

Component A has:

roomData: PropTypes.shape({
  roomId: PropTypes.number,
  roomType: PropTypes.string,
}).isRequired,

while Component B has:

roomData: PropTypes.shape({
  roomId: PropTypes.number.isRequired,
  roomType: PropTypes.string.isRequired,
  game: PropTypes.shape({
    gameId: PropTypes.number.isRequired,
    drawDescription: PropTypes.string.isRequired,
  }).isRequired,
}),

If both are COMPLETELY the same, I know how to do it. The problem is about them being different.

Gatsbimantico
  • 1,822
  • 15
  • 32
  • Possible duplicate of [ReactJS: How can I have a more modular use of prop types & shapes for objects?](https://stackoverflow.com/questions/29912334/reactjs-how-can-i-have-a-more-modular-use-of-prop-types-shapes-for-objects) – Hardik Modha Aug 29 '18 at 13:11

1 Answers1

0

Since PropTypes.shape expect a plain JS object, you can create an external file where you keep your shapes and use/combine them whenever you need it.

It'd be something like utils/propTypesShapes.js:

import PropTypes from 'prop-types'
export const transformToRequired = (shape) => {
  return Object.keys(shape).reduce((acc, curr) => {
    acc[curr] = shape[curr].isRequired;
    return acc;
  }, {})
}
export const roomDataBaseShape = {
  roomId: PropTypes.number,
  roomType: PropTypes.string,
}

Then in your components:

import { roomDataBaseShape, transformToRequired } from 'propTypes/shapes'
ComponentA.propTypes = {
  roomData: PropTypes.shape(roomDataBaseShape).isRequired
}

ComponentB.propTypes = {
  roomData: PropTypes.shape({
    ...transformToRequired(roomDataBaseShape),
    game: PropTypes.shape({
      gameId: PropTypes.number.isRequired,
      drawDescription: PropTypes.string.isRequired
    }).isRequired
  })
}
Alexandre Wiechers Vaz
  • 1,587
  • 2
  • 18
  • 21