Update React component with window.localStorage

Asked

Viewed 333 times

1

I’m new to React and I have the following problem: I have three components extends ComponentI need you to communicate.
They are a Navbar and two static contents.
Navbar content (text and icons) are changed according to the content (component) that is loaded.
The solution I found to upgrade Navbar was the window.localStoragesince I can’t leave the content as Navbar’s child components.
The render() of Navbar is conditional on each item of the localStorage.
The item of localStorage is being updated normally but it is not rendered on the screen. Is there any way to change state of componentswho are brothers and not children so as not to use the localStorage?

  • put the code you made. It’s better to have an opinion

1 answer

0

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:

Dados são passados do componente pai para o componente filho em ReactJS, dados são direcionais.

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/>
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.