r/reactjs•
mixuhd

preferred way to enforce prop shape

I have an list item called ThreadListItem. An item has a title and a body.

What is the 'best' way to define these props; Have an ES6 class for Thread, or use React.PropTypes.shape (Like Reddit Mobile does it https://github.com/reddit/reddit-mobile/blob/master/src/propTypes.es6.js#L30 ) or define all the props invidually?

  1. ES6 class

    // Thread.js class Thread { constructor(title, body) { this.title = title; this.body = body; } }

    // ThreadListItem.js class ThreadListItem extends React.Component { static propTypes = { thread: React.PropTypes.instanceOf(Thread) } ... }

  2. React.PropTypes.shape

    // Thread.js const Thread = React.PropTypes.shape({ title: React.PropTypes.string.isRequired, body: React.PropTypes.string.isRequired });

    // ThreadListItem.js class ThreadListItem extends React.Component { static propTypes = { thread: Thread } ... }

  3. Define all props invidually

    // ThreadListItem.js class ThreadListItem extends React.Component { static propTypes = { title: React.PropTypes.string.isRequired, body: React.PropTypes.string.isRequired } ... }

Skipped imports and exports from the examples, hope you understand. Any pros and cons with these different techniques?

ES6 class does not handle required/non-required properties or type checking, so thats why I mostly think using a shape would be the best way to go. Then again the ES6 class gives you an ability to create methods on the Thread class like excerpt() { return this.body.substring(0, 8) + '...' }

Posted Oct 22, 2016, 10:23 AM UTC · edited

01
goshakkk•

A class ties your component to that specific class instance, thus making it less reusable. Is there anything to justify using a class? There rarely is. That could be the case if the class were incapsulating some sort of behavior that you can't get with props alone.

Default to using plain props where you can. A component takes data and produces the view of that data.

If your component needs an excerpt, pass it with props! It helps clearly define what this particular component needs, and it does not care where that comes from. <ThreadListItem title={post.title} excerpt={post.excerpt()} /> is fine. Or you could let the component itself take care of the excerpt creating.

You can still have a thread class in your state, but as far as components go, their interface is just props and they shouldn't care how in particular that data is stored in the top-level component.

You may fee like repeating yourself a bit, but a bit of repetition is better than a bad abstraction.

As for props individually vs shape, I'd say go for individual. The component is called a thread item, after all, so it's a given that its props will be about a thread.

4