48

I have the following ReactJS class:

import React from 'react'

export class Content extends React.Component {

  static getValue(key) {
    return key
  }

  render() {
    let value = this.getValue(this.props.valueKey);
    return <span dangerouslySetInnerHTML={{__html: value}} />
  }
}

But I have the following error:

TypeError: this.getValue is not a function

I don't understand. Is this the good way to call a static function? I think react is doing something with statics, but I don't know what.

1
  • 1
    "is it the good way to call a static function ?" Since it doesn't work, probably not :P Commented Feb 27, 2016 at 18:06

2 Answers 2

61

A static method needs to be accessed on the class not an instance. So in your case, use:

Content.getValue()

However, a static method won't be able to access this -- I don't think you want the method to be static based on your code sample above.

More: Static Members in ES6

Sign up to request clarification or add additional context in comments.

1 Comment

The 'getValue' function itself is static - so it can be called with this.constructor.getValue(params)... I use this method often in my code. I don't see a reason for this function not to be static, unless 'this' needs to be called inside the function.
19

You can access from within the class as this.constructor.getValue.

Edit: I've added a JSFiddle here. The only change I made was adding the function call from the constructor and removing the dangerously set innerHTML - As shown, you can access the getValue static from this.constructor, and works just fine.

5 Comments

Not with React.Component
Incorrect - you can. Trust me on this one. I'll add a JSBin
@GeoffreyAbdallah this is very interesting. So you can also pass instance object as parameter to static class and can still access it is props like it is not not static. very cool
Interesting that we need to go though the constructor. Hm. Why is this?
@OliverDixon because "this.contrstructor" points on constructor function itself. so it's equal to Content.getValue but without need to hard code class name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.