reactjsreact-proptypes

How to define an exact (or shape) containing an array of the same exact?


I'm trying to define a PropTypes.exact (and the same could apply to PropTypes.shape) in which one of the props must be an array of the same exact.

This is what I have now, in a file which exports several shapes/exacts which are used in multiple components:

export const StatusLogLineShape = PropTypes.exact({
    dt: PropTypes.number.isRequired,
    indentLevel: PropTypes.number.isRequired,
    stat: PropTypes.number.isRequired,
    exp: PropTypes.boolean,
    msg: PropTypes.string.isRequired,
    children: PropTypes.arrayOf(StatusLogLineShape),
});

The code builds with no errors or warnings relating to the above, but loading the app in the browser produces the following console error, for the line with the children prop:

Uncaught ReferenceError: can't access lexical declaration 'StatusLogLineShape' before initialization

I understand why it throws an error, but is there any way to make this work?


Solution

  • I found a working solution after a bit more digging in Google results, as follows:

    const statLogLineShape = {
        dt: PropTypes.number.isRequired,
        indentLevel: PropTypes.number.isRequired,
        stat: PropTypes.number.isRequired,
        exp: PropTypes.bool,
        msg: PropTypes.string.isRequired,
    };
    statLogLineShape.children = PropTypes.arrayOf(PropTypes.exact(statLogLineShape));
    export const StatusLogLineShape = PropTypes.exact(statLogLineShape);
    

    This solution came from https://medium.com/@spencerwhitehead7/defining-recursive-proptypes-6f5586d0bd35