Home > front end >  Using the property of a PropType shape as the prop type for another component
Using the property of a PropType shape as the prop type for another component

Time:12-05

Is it possible to use a property of a PropType shape as the prop type for another component?

E.g.

function App({ data}) {
    return(
        <div>
            <Item item={data.item} />
        </div>
    )
}

const appPropTypes = PropTypes.shape({
    foo: PropTYpes.string.isRequired,
    item: PropTypes.string.isRequired,
});

App.propTypes = {
    data: appPropTypes;
};

function Item({ item }) {
     return <div>{item}</div>
}

Item.propTypes = {
    item: , // How can I refer to appPropTypes.item here?
}

Obviously the example above is very simple.

But in my actual use case, item is much more complex and I'd like to avoid having to have duplicate code in appPropTypes and itemPropTypes

CodePudding user response:

Not sure about accessing a particular PropType, since I believe they give you a function. So, instead of accessing the item property from PropTypes, you could probably just save item into it's own const and reuse it as necessary. Something like this:

const itemPropTypes = PropTypes.string.isRequired

const appPropTypes = PropTypes.shape({
    foo: PropTYpes.string.isRequired,
    item: itemPropTypes,
});

App.propTypes = {
    data: appPropTypes;
};
...

Item.propTypes = {
    item: itemPropTypes
}

CodePudding user response:

You can use appPropTypes.item if you move the call to PropTypes.shape to the where the data field is defined.

As here in this code snippet:

function App({ data }) {
  return(
      <div>
          <Item item={data.item} />
      </div>
  )
}

const appPropTypes = {  // PropTypes.shape moved below
  foo: PropTypes.string.isRequired,
  item: PropTypes.string.isRequired,
};

App.propTypes = {
  data: PropTypes.shape(appPropTypes), // PropTypes.shape moved here
};

function Item({ item }) {
   return <div>{item}</div>
}

Item.propTypes = {
  item: appPropTypes.item, // appPropTypes.item here
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App data={{foo:"bar", item:"myItem"}} />, rootElement);
<script src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/[email protected]/prop-types.js"></script>
<div id="root"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related