Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

propTypes isRequired constraint mis-leading behaviour in react

I'm very new to react( or to say web technologies). I started building an app which uses different components. When I went through the documentation, I thought putting isRequired in propTypes, constrains the user to provide all isRequired attributes when using the component.

But, in this example even if I don't pass isRequired attributes I'm able to load the component.

var PanelPreview = React.createClass({
    getInitialState: function(){
       return { captionIndex: 0 };
    },
    propTypes: {
       beforeSrc: React.PropTypes.string.isRequired,
       afterSrc: React.PropTypes.string.isRequired,
       captionTable: React.PropTypes.array
    },
});
module.exports = PanelPreview;

app using this component:

   React.render(
      < PanelPreview />,
      document.getElementById('main')
   );

I want to constrain the user of the component to provide these two values else throw some sort of error.

like image 263
mAc Avatar asked Nov 13 '14 12:11

mAc


1 Answers

Props failing validation isn't currently considered a critical error. However there will be a warnning logged in the console:

Warning: Required prop `beforeSrc` was not specified in `PanelPreview`.

This only happens in a non-production build of react. In production nothing is logged. See this fiddle for an example http://jsfiddle.net/5mafp3eu/1/

There has been discussion about having React fail-fast for prop validation failures (see issues below), it seems like it's going to happen eventually, but I don't think it's on any roadmap yet.

  • https://github.com/facebook/react/issues/1587
  • https://github.com/facebook/react/issues/1753
like image 185
WickyNilliams Avatar answered Oct 23 '22 10:10

WickyNilliams