Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS modify parent state from child component

Tags:

reactjs

state

I'm trying to remove an item from my state array when clicked. At the moment I have an onclick listener which calls a function passed into the props. However I get a warning: bind(): React component methods may only be bound to the component instance. See App... and it does not remove the item.

Thanks for any help regarding this issue! It has pretty much ground my progress to a halt.

(function (React) {

var data = [
    'Go to work',
    'Play Albion Online',
    'Keep learning React'
]

var App = React.createClass({
    getInitialState: function () {
        return {data: []}
    },
    componentWillMount: function () {
        this.state.data = data;
    },
    removeItem: function (i) {
        console.log(i);
    },
    render: function () {
        return (
        <ToDoList onRemoveItem={this.removeItem} tasks={this.state.data} />
        )
    }
});

var ToDoList = React.createClass({
    render: function () {

        var scope = this;

        var tasks = this.props.tasks.map(function (task, i) {
            return <ToDo onClick={scope.props.onRemoveItem.bind(this, i)} key={task} task={task} />
        });

        return (
        <ul>
            {tasks}
        </ul>
        )
    }
});

var ToDo = React.createClass({
    render: function () {
        return (
            <li>{this.props.task}</li>
        )
    }
});

React.render(<App />, document.getElementById('example'));
})(React);
like image 835
Monty Monro Avatar asked Feb 15 '15 09:02

Monty Monro


People also ask

Can child component change parent state React?

We can set Parent State from Children Component in ReactJs using the following approach. We will actually set the state of a parent in the parent component itself, but the children will be responsible for setting. We will create a function in parent to set the state with the given input.

How do you update parent state from child functional component?

React hooks are introduced in React 16.8. If you are familiar with the class components then there is no difference to change the parent component state from child component. In both cases, you have to pass the callback function to the parent.


1 Answers

React actually auto-binds methods to the current component:

http://facebook.github.io/react/blog/2013/07/02/react-v0-4-autobind-by-default.html

In the TodoList component, rather than:

scope.props.onRemoveItem.bind(this, i)

Try:

scope.props.onRemoveItem.bind(null, i)

By providing null instead of this you'll allow React to do its own thing. Also you need to actually use the onClick handler:

<li onClick={this.props.onClick}>{this.props.task}</li>
like image 110
Colin Ramsay Avatar answered Sep 28 '22 15:09

Colin Ramsay