Is not possible alter the state
of components
who are brothers, because React handles one-way data.
See the following schema to understand how React handles data between components:
Note that the data is not passed between the sister components, but received by the component father through the props
.
At the moment the data is changed in the parent component through the setState
, then Reactjs calls the method render()
of the parent component (and consequently of your children with the updated data).
A possible approach is to create a 'parent' component that stores the data your children will use. Thus, it is possible to pass on to the children the functions that manipulate this data (only the component itself must change its state
).
Below is a generic example of how this would be possible: the parent component has a variable numero
which is amended by a child:
class PaiDeTodos extends React.Component {
constructor(props) {
super(props)
this.state = { numero: 123 }
}
alterarNumero = (novoNumero) => {
this.setState({numero: novoNumero});
}
render () {
return <Navbar/>
<ConteudoEstatico this.props.alterarNumero=alterarNumero>
}
}
Child component received through the props
the function alterNumber, which will be called at the click of the button and by changing the state
of the father, will cause the method call render()
of the father:
class ConteudoEstatico extends React.Component {
cliqueBotao = () => {
this.props.alterarNumero(555);
}
render () {
return <button onClick={this.cliqueBotao}>Clique aqui.<button/>
}
}
put the code you made. It’s better to have an opinion
– Danilo Cândido