16

I have the following widget class:

var Widget = React.createClass({
    statics: {title: "a title"},
    ...
});

Is there a way of accessing the title static inside the class'es methods (using this)? For example:

render: function() {
    return <div>{this.title}</div>;
}
1
  • you cannot access statics within the class. You can only do Widget.title Commented Feb 25, 2015 at 17:35

3 Answers 3

19

You can access a static from within the component from this.constructor:

so in this case it would be:

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

1 Comment

Is this documented? If so could we get the link?
8

The direct answer:

React.createClass({
    title: 'a title',
    render: function() {
        return <div>{this.title}</div>;
    }
});

Or:

React.createClass({
    componentWillMount: function(){
        this.title = 'a title';
    },
    render: function() {
        return <div>{this.title}</div>;
    }
});

But really... why not just use a variable?

var TITLE = 'a title';

React.createClass({
    render: function() {
        return <div>{TITLE}</div>;
    }
});

3 Comments

Be warned, in example #3 TITLE will be static and shared among every instance of the class.
Yes, I believe that was the intention here because the OP mentioned statics.
My bad, I misread the question. My preferred style is your example #3 by a long shot.
7

The statics object of a React Class is a way to define static methods (i.e., methods that don't need any context to run). That being said, it doesn't make sense to call a static method from this.

It looks like you're looking for a "static" property (i.e., non-mutable). So, you should use it like this.props.title on render(). To set the value of title, you should do <Widget title='a title'/>. It worths mentioning that you can set default properties, by defining the getDefaultProps method.

More about statics and about props on React's doc.

Comments

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.