How can I centralize proptypes which are not the same

436 views Asked by At

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.

1

There are 1 answers

0
Alexandre Wiechers Vaz On

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
  })
}