Update React component with window.localStorage [closed]

1

I'm new to React and I have the following problem: I have three components extends Component that I need to communicate.
They are a NavBar and two static contents.
The contents of NavBar (text and icons) are changed according to the content (component) that is loaded.
The solution I found to update the NavBar was window.localStorage since they are I can not leave the contents as child components of NavBar.
The render() of NavBar is conditional for each item of localStorage .
The localStorage item is being updated normally but it is not rendered on the screen. Is there any way to change state of components that are siblings and not children so you do not need to use localStorage ?

    
asked by anonymous 26.10.2018 / 01:10

1 answer

0

Unable to change state of components that are siblings , because React handles unidirectional data.

See the following schema to understand how React handles data between components:

Note that the data is not passed between the sibling components but is received by the parent component through props .

When the data is changed in the parent component by setState , then ReactJS calls the render() method of the parent component (and consequently its children with the updated data).

One possible approach is to create a 'parent' component of the components that stores the data your children will use. Thus, it is possible to pass to the children the functions that manipulate this data (only the component itself should change its state ).

Below is a generic example of how this would be possible: the parent component has a numero variable that is changed 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 by props the function changeNumber, which will be called at the click of the button and by changing the state of the parent, will cause the parent% method call:

class ConteudoEstatico extends React.Component {

  cliqueBotao = () => {
    this.props.alterarNumero(555);
  }

  render () {
    return <button onClick={this.cliqueBotao}>Clique aqui.<button/>
  }
}
    
26.10.2018 / 04:46