Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static propTypes not working under ES6

I want to add some rules for props:

import React, { Component } from 'react'

export default class App extends Component {
  static propTypes = { name: React.PropTypes.string.isRequired };

  render() {
    return(
    )
  }
}

But I got this an error:

Warning: Failed prop type: Required prop `name` was not specified in `App`.

I have this configuration for babel:

{
  "presets": ["es2015", "react"],
  "plugins": ["transform-runtime", "transform-class-properties"]
}

What I did wrong?

Upd. Change code: use static

like image 667
Pavel Avatar asked Jul 13 '16 23:07

Pavel


Video Answer


2 Answers

It appears the you aren't transpiling your code in a way that can recognize static class properties. If you are using babel this can be enabled by using the Class Property Transform : https://babeljs.io/docs/plugins/transform-class-properties/.

In our code base we get this functionality with the Stage 1 preset, https://babeljs.io/docs/plugins/preset-stage-1/

Of course you could always define your proptypes on the class:

export default class App extends Component {
  ...
  render() {
    ...
  } 
}

App.propTypes = {
 data: PropTypes.object.isRequired...
}

^^ this doesn't require any special transpilation.

The in class static property is nice though so you can set it up like this

export default class App extends Component {
  static propTypes = { name: React.PropTypes.string.isRequired };
  render() {...} 
}

rather than define the propTypes on this in the constructor.

like image 162
JizoSaves Avatar answered Oct 13 '22 16:10

JizoSaves


I'm leaving this answer for the comments but Timothy's answer regarding Babel is better.


In ES6, classes have methods, and that's it--not even properties, let alone static:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

ES2017 may support a different property mechanism:

https://esdiscuss.org/topic/es7-property-initializers

This question is strongly related to ES6 class variable alternatives and is ultimately probably a dupe.

like image 32
Dave Newton Avatar answered Oct 13 '22 17:10

Dave Newton