Skip to content Skip to sidebar Skip to footer

Reactjs: How Can I Have A More Modular Use Of Prop Types & Shapes For Objects?

I like to explicitly specify all my prop types for every class. React.createClass({ propTypes: { optionalArray: React.PropTypes.array, optionalBool: React.PropTypes.bool,

Solution 1:

I had the same problem and just moved the values to a separate ES6 module. In your example:

// File lib/PropTypeValues.js
import { PropTypes } from'react';

export let MemoryPropTypes = PropTypes.shape({
  memoryID: PropTypes.number,
  content: PropTypes.string,
  date: PropTypes.object,
  dateStr: PropTypes.string,
  note: PropTypes.string
}).isRequired

Then in your client code:

// MemoryForm.jsximport { MemoryPropTypes } from'./lib/PropTypeValues'importReactfrom'react';

classMemoryFormextendsReact.Component {
  staticpropTypes: {
    memory: MemoryPropTypes,
    // ...
  };
}

Hope this helps.

Solution 2:

I would make a small module exposing that functionality. It would look something like this in a CommonJS world:

letReact = require('react');

module.exports = {
  propTypes() {
    returnReact.PropTypes.shape({
      memoryID: React.PropTypes.number,
      content: React.PropTypes.string,
      date: React.PropTypes.object,
      dateStr: React.PropTypes.string,
      note: React.PropTypes.string
    }).isRequired;
  },
  initialValues() {
    return {
      memoryID: 0,
      content: "",
      date: null,
      dateStr: "",
      note: ""
    };
  }
}

Then you'd use that in components like this:

let memoryUtils = require('./memory-utils');

letMyComponent = React.createClass({
  propTypes: memoryUtils.propTypes(),
  render() {
    ...
  }
});

And:

let memoryUtils = require('./memory-utils');

letMyComponent = React.createClass({
  getInitialState() {
    return memoryUtils.initialValues();
  },
  render() {
    ...
  }
});

Post a Comment for "Reactjs: How Can I Have A More Modular Use Of Prop Types & Shapes For Objects?"