JacobIRR
JacobIRR

Reputation: 8946

how to access "this" from component method

I've got this little component which is supposed to post to the server with each change:

class SelectElement extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            optionList: []
        };
    }

    finalize() {
        // this means "window" in this case... so all the code below barfs:
        let key = this.props.inputName;
        let val = this.state.text;
        let postObj = {};
        postObj[key] = val;
        console.dir(postObj);
        $.post($.endPoints.saveCallField, postObj).done(function (response) {
            console.dir(response);
        });
    }

    render() {
        this.props.options.forEach(option =>
            this.state.optionList.push(<OptionElement value={option} text={option }/>)
        );
        return (
            <React.Fragment>
                <select className="form-control callField" name={this.props.inputName}
                        onChange={this.finalize}>
                    {this.state.optionList}
                </select>
            </React.Fragment>
        );
    }
}

I can't get access to "this" where "this" is the SelectElement itself. I need the state and props. How can I get it?

Upvotes: 0

Views: 41

Answers (2)

J. Kamien
J. Kamien

Reputation: 51

It looks like you've identified the issue. When the finalize() method is called, this is bound to the window.

You can solve the issue by binding the function in the constructor. For example:

    constructor(props) {
            super(props);
            this.state = {
                optionList: []
            };
            this.finalize = this.finalize.bind(this);
        }

It's generally better to bind in the constructor than to bind in the render method, because if you call bind in the render method, you are generating a new function each time.

For more information, take a look at this: https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56

Upvotes: 1

radzak
radzak

Reputation: 3118

Use one of these:

  1. this.finalize = this.finalize.bind(this); in constructor
  2. onChange={this.finalize.bind(this)}
  3. onChange={e => this.finalize(e)}
  4. finalize = () => {};

You can read more about the pros and cons here.

Upvotes: 3

Related Questions