how can I update a component from another in react js?
I read a lot of post but i'm not able to find my case.
I have 3 react class: Main class that contains my two react components:
`React Component A
`
I would like to update the state of the component A using the component B.
UPDATE 1/2
I'm trying to follows the steps as you suggested but i have this problem:
i define a function in my main class:
handleArticleUpdate(codice){
alert(codice);
//this.setState({codice_articolo: codice});
}
And i'm trying to inject it in my component:
<MainGrid onArticleChanged={this.handleArticleUpdate} />
But i receive the error:
TypeError: Cannot read property 'handleArticleUpdate' of undefined
I tryed to bind the this too but the error is the same..
MY CODE:
import React, { Component, PureComponent } from 'react';
import { NavLink } from 'reactstrap';
import ReactDOM from 'react-dom';
import {Form, TabPanel} from 'devextreme-react';
import MainGrid from './components/MainGrid';
import VisualizzatoreArticoli from './components/VisualizzatoreArticoli';
import './App.css';
const headerStyle ={
border:'1px solid'
}
const contentStyle ={
border: '1px solid'
}
const bodyStyle ={
backgroundColor: '#999999'
}
//import { Loading } from '../../../theme-
sources/bootstrap4/components/loading';
//import { CurrencyTypeProvider } from '../../../theme-
sources/bootstrap4/components/currency-type-provider';
const URL = 'http://localhost:53139/api/randomData';
//const URL = 'https://js.devexpress.com/Demos/WidgetsGallery/data/orderItems';
class App extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
itemsHeader : [
{
title : 'a',
badge: 'New'
},
{
title : 'b',
text : "1",
},
{
title : 'c',
},
],
itemsContent : [
{
title : 'Righe',
badge: 'New'
},
{
title : 'b',
text : "1",
},
{
title : 'c',
},
],
codice_articolo :''
}
this.handleArticleUpdate = this.handleArticleUpdate.bind(this);
}
getInitialState(){
return this.state.codice_articolo
}
handleArticleUpdate(codice){
alert("");
//this.setState({codice_articolo: codice});
}
render() {
return (
<div style={bodyStyle}>
<div style={headerStyle}>
<TabPanel
height = '300'
items = {this.state.itemsHeader}
itemComponent = {function(itemData){
switch(itemData.title){
case "a":
return null
break;
case "b":
return null
break;
case "c":
return null
break;
}
}
}
>
</TabPanel>
</div>
<br />
<div style={contentStyle}>
<TabPanel
height = '700'
items = {this.state.itemsContent}
itemComponent = {function(itemData){
switch(itemData.title){
case "Righe":
return <MainGrid onArticleChanged={this.handleArticleUpdate()} />
break;
case "b":
return null
break;
case "c":
return null
break;
}
}
}
>
</TabPanel>
</div>
</div>
);
}
}
export default App;
UPDATE 2/2
I think my problem is that my component is too nested (it's inside the component TabPanel) and handleArticleUpdate is not visible in the scope.
I tryed put only
<MainGrid onArticleChanged={this.handleArticleUpdate} />
in the render() function and all worked perfectly.