0

I was into functional Javascript previously, Recently I started with Object oriented Javascript and React Library. This question is more of understanding the code.

Why below code don't work

class MyComponent extends React.Component{ propTypes : { name: React.PropTypes.string.isReequired, location: React.PropTypes.string } render(){ return( <h1>Hello This is {this.props.name} and I live in {this.props.location}</h1> ); } } ReactDOM.render( <MyComponent name="Node" location="DOM"/>, document.getElementById('root') ); 

Whereas this code works,

class MyComponent extends React.Component{ render(){ return( <h1>Hello This is {this.props.name} and I live in {this.props.location}</h1> ); } } MyComponent.propTypes = { name: React.PropTypes.string.isReequired, location: React.PropTypes.string } ReactDOM.render( <MyComponent name="Node" location="DOM"/>, document.getElementById('root') ); 

Can someone help me understand this? Thanks.

2 Answers 2

3

You need to use static word (to define the static property) because, propTypes need to be declared on the class itself, not on the instance of the class , and use =.

Check the DOC.

Like this:

static propTypes = { name: React.PropTypes.string.isRequired, location: React.PropTypes.string } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. This makes sense :)
2

Inside an ES6 class, static properties look like this

class X extends Y { static staticThing = { ... } } 

note the =

"assigning" a static property the ES5 way looks like the second way you have it there

Typically, you'll use the second way for functional components whereas you might as well use the first way (albeit properly with an =) for ES6 style class components.

also, make sure you have your React.PropTypes correct - isReequired should be isRequired

1 Comment

Thank you. Now i understood.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.