0
People started using React recently, and I have a problem. I need that when the user clicks on the Mycomponent button the increment is shown in the App.
export default class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
itemCount: 0
};
}
addItem() {
this.setState({
itemCount: this.state.itemCount + 1
});
}
render() {
return (
<div>
<button onClick={this.addItem.bind(this)}>Click Me</button>
<h1 >Current Item Count: {this.state.itemCount}</h1>
</div>
);
}
};
class App extends Component {
constructor(props) {
super(props)
this.child = React.createRef();
this.state = {
itemCount: 0
}
}
onClick = () => {
this.child.current.addItem();
};
render() {
return (
<div>
<MyComponent ref={this.child} />
</div>
);
}
}
export default App;
The way it is being done, the value is not passed to the App.
you have to learn some state management tool, like: Redux, Mobx, Flux, etc. Or you can learn about Context
– Alex
Oh great, thanks. I’ll learn about Redux. For this purpose, I ended up using the localstorage. You recommend ?
– Mateus Moreira
I don’t know what kind of purpose you would use the Torage localStorage for in real life, but like you said "the value is not passed to the App" so I really recommend using a state manager
– Alex
All right. Thank you.
– Mateus Moreira