Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Static Methods in React


    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.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    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.

    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.

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

    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.

    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.

    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.