Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React update state in parent from child components

I have child components that receive props from a parent, but on an event (button click) in a child I want to setState again with the new props. So the parent passes down all items in a list to the children. In the child prop a button deletes an item in the list. But how can you update the state so the list item is also removed from the view. This is my code:

const Parent = React.createClass({
    getInitialState:function(){
        return {
            items: []
        };
    },
    componentWillMount:function(){
        axios.get('/comments')
            .then(function(response) {
                this.setState({
                    items: response.data
                })
            }.bind(this));
    },
    render() {
        return (
            <div>
                <Child1 data={this.state.items}/>
            </div>
        );
    }
});

export default Parent;

export default function Child1(props){
    return(
        <div>
            { props.data.map((comment,id) =>(
                    <p key={id}>
                        {comment.name}<Delete data={comment.id}/>
                    </p>
                )
            )}
        </div>
    )
}

class Delete extends React.Component {
    constructor() {
        super();
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
        Purchase.Action(this.props.data,'remove');
        axios.post('/comments', {
            item: this.props.data
        })
        .then(function (response) {
            console.log(response.data);     
        })
        .catch(function (error) {
            console.log(error);
        });
    }

    render() {
        return <Button onClick={this.handleClick}>Delete</Button>;
    }
}

module.exports = Delete;

So although the comment is deleted at the server, I want to delete the comment from the component view by updating the state.

like image 767
user94628 Avatar asked Oct 17 '16 12:10

user94628


People also ask

How do you update parent state from child component React?

We will create a function in parent to set the state with the given input. We will pass that function in children as a prop. Then Children will call the function with a new Value. We will set the state of the parent in the function.

Is it possible to change parent component state from the child component?

To update the parent state from the children component, either we can use additional dependencies like Redux or we can use this simple method of passing the state of the parent to the children and handling it accordingly.

How do you access the state in the parent component from a child component?

In React we can access the child's state using Refs. we will assign a Refs for the child component in the parent component. then using Refs we can access the child's state. Creating Refs Refs are created using React.

Does React update all children components once the state of a parent has changed?

As a result, the child components only update when the parent component's state changes with one of those functions. Directly mutating the props object is not allowed since this won't trigger any changes, and React doesn't notice the changes.


1 Answers

If you want to delete the comment from the component, you have to update your Parent state.

In order to do that you can create a new method, delete(id), in your Parent component where you remove the deleted item from the state.

const Parent = React.createClass({
    getInitialState:function(){
        return {
            items: []
        };
    },
    componentWillMount:function(){
        this.setState({
            items: [
            {id: 1,name: "Name 1"},
            {id: 2,name: "Name 2"},
            {id: 3,name: "Name 3"}
          ]
        })
    },
    delete(id){
      // axios.post(...)
      let items = this.state.items.filter(item => item.id !== id);
      this.setState({items});
    },
    render() {
        return (
            <div>
                <Child1 
                   data={this.state.items} 
                   handleClick={this.delete} // Pass the method here
                />
            </div>
        );
    }
});

function Child1(props){
    return(
        <div>
            { props.data.map((comment,id) =>(
                    <p key={id}>
                        {comment.name}
                        <Delete 
                           data={comment.id}
                           handleClick={() => props.handleClick(comment.id)} // Pass the id here
                        />
                    </p>
                )
            )}
        </div>
    )
}

class Delete extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        return <button onClick={this.props.handleClick}>Delete</button>;
    }
}

jsfiddle

like image 125
QoP Avatar answered Sep 24 '22 22:09

QoP