Skip to content Skip to sidebar Skip to footer

Alter State Of Parent From A Child Component React Js

class Parent extends React.Component{ constructor(props){ super(props); this.state={ data : props.data }; } render(){ for(let i=0;i

Solution 1:

You need to update the data in the parent object and let React handle the child updates itself. An example of how that would look is:

classParentComponentextendsReact.Component {
    onChangeValue = (index, newData) => {
        let data = this.state.data;
        data[index] = newData;

        this.setState({ data });
    }

    render() {
        let outs = [];

        for (let i = 0; i < 10; i++) {
            let row = this.state.data[i];

            outs.push(
                <ChildComponentindex={i } row={row } onChangeValue={this.onChangeValue }/>
            );
        }

        return<div>{ outs }</div>;
    }
}

classChildComponentextendsReact.Component {
    ...

    onChangeValue() {
        const { index, onChangeValue } = this.props;
        this.props.onChangeValue(index, { someNewValue });
    }
}

when you want to update something in the child, you'd call its onChangeValue method which, in turn, calls the parent's onChangeValue.

Post a Comment for "Alter State Of Parent From A Child Component React Js"