Static Methods in React

Joe Maddalone
InstructorJoe Maddalone
Share this video with your friends

Social Share Links

Send Tweet
Published 9 years ago
Updated 5 years ago

The statics object of our React view components is meant to contain values or functions that can be accessed at any time without needing an instance of that component created.

[00:01] Statics are a way for us to access functionality within our component before we've ever rendered that component. What we're going to do here is create a quick little react component. We'll just call it App, and in our render method we're just going to return null.

[00:16] Now we're going to add a statics object, so that is an object, and inside of that object we can pass in our function. We're just going to create a quick add function that's going to take in x and y. Then it is going to console.log. The answer is x+y.

[00:36] Now we can actually access this by simply calling our app variable, so App.add(5,8) should return, the answer is 13. Awesome.

[00:47] Now let's go ahead and add our component to the document. Let's actually render it out to the document.body. Now if we try to access our instances add method from the statics, it's not going to work. We'll go ahead and run this, and we obviously get undefined. In addition to that, if we try to access it inside of our render method with this.add, we also get undefined.

[01:20] The way to access this is the same way we accessed it before we rendered it with just App.add. Now we get the answer is 10. From within our component, we can also access this.constructor.add. Let's enter 5 and 6, and we get the answer is 11.

[01:40] Now since our static methods are available before we render, they have no access to props or state within our component. So if we add a prop here of x={5}, what we can do is call our static method, App.add, and we can pass in the props from our instance, so props.x, pass in a 10, and we should get the answer is 15. There you go. That is a quick look at statics in your react component.

egghead
egghead
~ 41 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today