Search code examples
javascriptreactjsreactjs-fluxfluxible

Reactjs and this is undefined


I m actually trying to develop a simple application using stores and actions and react components using fluxible and I m facing a problem.

In fact, in my component method add(), "this" is undefined...

I dont know what is the problem...

Here's my component:

import React from 'react';

class Client extends React.Component {

    constructor (props) {
      super(props);
    }

    add(e){
      this.context.dispatch('ADD_ITEM', {name:'Marvin'});
    }

    render() {
        return (
            <div>
                <h2>Client</h2>
                <p>List of all the clients</p>
                <button onClick={this.add}>Click Me</button>
                <ul>
                </ul>
            </div>
        );
    }


}

Client.contextTypes = {
    dispatch: React.PropTypes.func.isRequired
};

export default Client;

Solution

  • Try this for your button:

    <button onClick={this.add.bind(this)}>Click Me</button>