de__bug de__bug - 18 days ago 9
React JSX Question

Validate propTypes on parent and child components?

Should I be adding propTypes to parent components and their child components?

For example I have a

<Header modal={this.state.modal} lives={this.state.lives} score={this.state.score} />
component that is passed 3 props and I validate like so:

const Header = function(props) {
if (props.modal) {
return (<Logo logo={logo} />);
} else {
return (
<div>
<Lives lives={props.lives} />
<Score score={props.score} />
</div>
);
}
};
Header.propTypes = {
modal: React.PropTypes.bool.isRequired,
lives: React.PropTypes.number.isRequired,
score: React.PropTypes.number.isRequired,
};


As you can see there are two child components
<Lives lives={props.lives} />
and
<Score score={props.score} />
. I've added propTypes to those components as well.

const Score = function(props) {
return (
<p className="score score--right">
{props.score} pts
</p>
);
};
Score.propTypes = {
score: React.PropTypes.number.isRequired,
};


So is it redundant to be checking the same props twice? And is this just overcomplicating things (making my code more difficult to manage).

Answer

In my opinion, you should validate propTypes in every components regardless of whether it has been validated in the parent component. Think like: If a component uses a prop, you should validate the type of the prop

One of the major advantage of React is component re-usability. Even in you case, the Score may be only used by Header at the moment, you may later on find it useful in other places and Score is getting score from other sources, you should make sure it receives the correct type.

If you are worried the bundled size from these duplication of proptype validations in production, there is a bable plugin to help with that.