Reputation: 849
I have a question about changing child state value from the parent.
I have a design like on the image below. When a datagridrow is selected, row info is sent to datagrid and parent components. Datagrid component keep selectedRowId info in its state, Parent keeps this as well. Parent component has a form and when a row is selected, form elements are filled. When I save the form, I want to clean row selection in the grid. But I cannot find how I can clean datagrid state info(selectedrowId).
I want keep my datagrid component isolated from redux because I want to use datagrid like packaged library. Also I do not want to use ref.
I tried several things but cannot be successful.
Any help would be appreciated, thanks.
Upvotes: 1
Views: 1224
Reputation: 17239
I might be misunderstanding the question, but would something like this work?
import React from "react";
import ReactDOM from "react-dom";
class A extends React.Component {
state = {
items: [0, 1, 2],
selected: 0
};
select = val => {
this.setState({
selected: val
});
};
reset = () => {
this.setState({
selected: 0
});
};
render() {
return (
<React.Fragment>
<B {...this.state} select={this.select} />
<button onClick={this.reset}>reset</button>
</React.Fragment>
);
}
}
class B extends React.Component {
render() {
return (
<C
items={this.props.items}
select={this.props.select}
selected={this.props.selected}
/>
);
}
}
class C extends React.Component {
render() {
const { items, selected } = this.props;
return items.map(i => (
<div
onClick={() => this.props.select(i)}
style={{ color: i === selected ? "red" : "black" }}
>
{i}
</div>
));
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<A />, rootElement);
Working example here.
Upvotes: 2