Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React js and PropTypes repetition across shared components

I've created some react components and as such, the parent... gets a few props...

Every subsequent child then uses most of these props, then children of children.

**--> Parent**
(required props)
**-------> child**
(required props)
**-------> child**
(required props)
**------------> sub child**
(required props)
**------------> sub child**

those "required props" are the same for all those components. Seems excessive that whenever I update a prop in Parent, I then have to go into all those children and update to (if they are required). Of course, they are required and needed, but curious if there is a shortcut/or implementation that this repeating is not necessary. Any ideas?

Thanks

like image 354
user1492442 Avatar asked May 15 '15 17:05

user1492442


2 Answers

You can store your prop types in an object that you merge into the each component's propTypes:

var requiredPropTypes = {
    foo: ...,
    bar: ...
};

var ComponentA = React.createClass({
    propTypes: {
        ...requiredPropTypes,
        // ComponentA's prop types follow
        // ...
    },
    // ...
});

var ComponentB = React.createClass({
    propTypes: {
        ...requiredPropTypes,
        // ComponentB's prop types follow
        // ...
    },
    // ...
});

The value of propTypes is just an object. How you build that object is completely up to you.

like image 66
Felix Kling Avatar answered Sep 30 '22 22:09

Felix Kling


This is pretty simple. If your writing es6 code, you can use the shape of a component that you import

import React, { PropTypes } from 'react';    
import { Button } from 'components';

const NewComponent = (props) => {
    return (
        {props.buttons.map((button) =>
            <div>
                <Button {...props} />
            </div>
        )}
    );
}

NewComponent.propTypes = {
    buttons: PropTypes.arrayOf(PropTypes.shape({ Button }.propTypes))
};
like image 38
Jason Law Avatar answered Sep 30 '22 23:09

Jason Law