5

I am creating a component (- child) like npm package (- another project). This component will by use in another component (- parent) (will be installed like npm i child).

So, my problem is that I want to use redux store architecture in a child. In the parent, there is a too redux store architecture. In a child, I don't want to use own store I want to use the store of the parent component. How can I do this? How can I use the store of parent component in my child?

It is possible? I don't have any idea how to do it.

Thank you for any help.

2 Answers2

1

I can suggest you two options:
1) Make a reducer of your child component and pass it to combineReducer in your reducer configuration. Then you will have access to global store.
2) Or you can simply pass whatever your child consumes from parent component as a props.

AkshayM
  • 1,421
  • 10
  • 21
  • How can I pass store into my child, its not accessible while I using ... –  Oct 29 '18 at 10:48
1

I think there are more the one ways how to do it.

I prefer way with combine reducers.

In your child app create some reducer:

import {ACTIONS} from './actions';

const defaultState = {
    counter: 0,
};

export default function(state = defaultState, action) {
    switch (action.type) {
        case ACTIONS.PLUS:
            let newState = {...state};
            newState.counter++;
            return newState;
        case ACTIONS.MINUS:
            let newState2 = {...state};
            newState2.counter--;
            return newState2;
        default:
            return state;
    }
};

Export this reducer from project: export {default as YourReducer} from './your-reducer';

Now, in parent root reducer combine this reducer:

import {combineReducers} from 'redux'

import app from 'app/containers/app/app-reducer'
import {YourReducer} from '@this-is-your-package/YourReducer'

export default combineReducers({
    app,
    YourReducer,
})

So, its all, now you can use connect, mapStateToProps, dispatchToProps, etc... in your child.

You can read parent state store too..

Parent store looks like this:

app: { ... }         // <-- parent
YourReducer: { ... } // <-- your child
JaLe
  • 409
  • 3
  • 13