Tzach
Tzach

Reputation: 13406

Using React.js statics inside class methods

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>;
}

Upvotes: 16

Views: 14531

Answers (3)

cyberglot
cyberglot

Reputation: 395

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.

Upvotes: 7

user5004821
user5004821

Reputation:

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

so in this case it would be:

this.constructor.title

Upvotes: 19

Brigand
Brigand

Reputation: 86260

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>;
    }
});

Upvotes: 8

Related Questions