Search code examples
javascriptreactjsreact-props

How to handle PropTypes inside array component?


I have the following construct:

import PropTypes from 'prop-types';
import TitleCell from '../components/TitleCell/TitleCell';

const list = [
    {
        title: 'some title',
        height: '50px',
        render: ({ width }) => (
            <TitleCell
                value={width}
            />
        ),
    },
];

list.propTypes = {
    width: PropTypes.string.isRequired,
};

I am still getting error "error 'width' is missing in props validation". How can I correct this?


Solution

  • It may be some static code analysis that is interpreting the render function as an anonymous functional React component and is thus reporting that propTypes needs to be defined.

    Define a local named component and attach defined propTypes.

    import PropTypes from 'prop-types';
    import TitleCell from '../components/TitleCell/TitleCell';
    
    const RenderComponent = ({ width }) => <TitleCell value={width} />;
    
    RenderComponent.propTypes = {
      width: PropTypes.string.isRequired,
    };
    
    const list = [
      {
        title: 'some title',
        height: '50px',
        render: RenderComponent,
      },
    ];