Valay
Valay

Reputation: 1999

React/Redux - Update state in parent component from child component

I've 2 components: Header and Child in an already developed react application that uses redux-saga.

Header component has 2 material-ui Select component. Now when I route to child component I want to disable those 2 Select component in Header by updating it's state.

App.js

const App = ({ store }) => {
  return (
    <ThemeProvider theme={theme}>
      <Provider store={store}>
        <Header />
        <Router />
        <Footer />
      </Provider>
    </ThemeProvider>
  );
};

Router.js

<Route
        exact
        path={`${url}BatchFileRawDataDashboard`}
        component={Child}
      />

Header.js

<Select
  style={{ width: 112 }}
  value={this.state.selectedCycle}
  autoWidth={true}
  disabled={this.disableCycle.bind(this)}
 >
 {cycleDateItem}
 </Select>

Header component has no props and I am very much confused with how mapStateToProps and mapDispatchToProps works.

How to update state of parent component from child component that uses redux?

Upvotes: 0

Views: 4067

Answers (1)

Luke Robertson
Luke Robertson

Reputation: 1652

mapStateToProps = putting redux store state into the props

mapDispatchToProps = putting redux actions into the props

So on the child, you want to call an action that will update the store via mapDispatchToProps

Then on the parent you want to use mapStateToProps to read this updated value

// PARENT READ DATA

const mapStateToProps = (store) => ({
  parentData: store.parentData,
})


// CHILD ACTION TO UPDATE STORE

// the function here triggers a action which triggers a reducer
const mapDispatchToProps = dispatch => ({
  updateParentAction: data => dispatch(some_action_name(data)),
})

I suggest reading up on how redux works, it's simple once you get it, but complicated to start with https://www.valentinog.com/blog/redux/

Upvotes: 3

Related Questions