Search code examples
reactjsstyled-componentsreact-proptypes

Why am I getting an invalid prop type warning?


I have the following component:

import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { Box } from 'grid-styled';

const Pane = ({
  children,
  px,
  py,
}) => (
  <StyledBox
    px={px}
    py={py}
  >
    {children}
  </StyledBox>
);

Pane.propTypes = {
  children: PropTypes.node.isRequired,
  px: PropTypes.oneOfType([PropTypes.number, PropTypes.arrayOf(PropTypes.object)]),
  py: PropTypes.oneOfType([PropTypes.number, PropTypes.arrayOf(PropTypes.object)]),
  marginBottom: PropTypes.number,
  color: PropTypes.string,
};

Pane.defaultProps = {
  px: [null],
  py: [32, 40],
};

export default Pane;

My web-client's JS console is warning with the following:

preview.bundle.js:4294 Warning: Failed prop type: Invalid proppysupplied toPane. in Pane

Why?


Solution

  • py: [32, 40], is an array of numbers while you declare it should be PropTypes.arrayOf(PropTypes.object) - an array of objects. It's not the same.

    py: PropTypes.oneOfType([PropTypes.number, PropTypes.arrayOf(PropTypes.number)]),
    

    This means it will be a single number like 4 or an array of numbers like [32, 40].