Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React setState between components ES6

I have a very simple application where I am trying to update the state of a parent component from a child component as follows:

import React from '../../../../../../../dependencies/node_modules/react';
import ReactDOM from '../../../../../../../dependencies/node_modules/react-dom';

class CalendarMain extends React.Component {
    constructor() {
        super();
    }

    handleClick() {
        this.props.handleStateClick("State Changed");
    }

    render() {
        return ( 
            <div>
                <div className="calendar">
                    {this.props.checkIn}
                    <button onClick={ this.handleClick.bind(this) }>Click Me</button>
                </div>
            </div>
        )
    }
}

class CalendarApp extends React.Component {

    constructor() {
        super();

        this.state = { 
            checkIn: "Check-in",
            checkOut: "Check-out",
            dateSelected: false 
        };
    }

    handleStateClick( newState ) {
        this.setState({
            checkIn: newState
        });
    }

    render() {

        return (
            <div>
                <CalendarMain 
                    checkIn = { this.state.checkIn }
                    handleStateClick = { this.handleStateClick.bind(this) }
                />
            </div>
        );
    }
}

The error I am receiving is this.setState is not a function and I can't work out why. Any help would be much appreciated!

like image 744
Tom Pinchen Avatar asked Jun 15 '26 12:06

Tom Pinchen


1 Answers

this is not auto-bound in ES6 style syntax.

Either:

  1. Bind in constructor like so: this.func = this.func.bind(this)
  2. Use arrow function syntax for the function in question like so: func = () => {};

More here: https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding

like image 173
pmilla1606 Avatar answered Jun 18 '26 01:06

pmilla1606



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!