Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Static Methods in React

    Joe MaddaloneJoe Maddalone

    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.

    reactReact
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss