简体   繁体   中英

State and routing for imported React components

I have to write an integrated chat module that has two versions - a small in-site window (like facebook messenger) and full version that is opened in a new tab (a new react-router route). So, this module exports two components: <ChatWindow /> and <ChatFullView /> for these views respectively.

// core application
import {ChatWindow, ChatFullView} from 'chat-module';


// <PageContentWithChat /> contains imported <ChatWindow />
<Switch>
    <Route path='/' component={PageContentWithChat} />
    <Route path='/fullview' component={ChatFullView} />
</Switch>

So, the question is:
Where should I declare the redux store and manage it for both of them? (They must have one united store because the messages from the window version should be rendered in full view and vice versa)

EDIT: I wanted to control the module from the inside:

// in module
const store = createStore(reducer);

....
<Provider store={store}>
    <ChatWindow />
    <ChatFullView />
</Provider>

But I'm afraid I won't be able to export these components separately as they are wrapped with <Provider /> . How is it possible to solve this?

react-redux makes the store available through context via the Provider component.

Assuming <ChatWindow /> and <ChatFullView /> are connected components, you would wrap everything in <Provider /> , passing in your store as a prop.

Of course, you can organize all of this into different files, but this is the general idea.

import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Switch, Route } from 'react-router';
import { BrowserRouter } from 'react-router-dom';
import { createStore } from 'redux';
import PageContentWithChat from 'path-to-page-content-with-chat';
import { ChatWindow, ChatFullView } from 'chat-module';

const store = createStore(/* reducers + initial message state passed in here... */);
const container = document.getElementById(/* id of your app container */);
const component = (
  <Provider store={store}>
    <BrowserRouter>
      <Switch>
        <Route path='/' component={PageContentWithChat} />
        <Route path='/fullview' component={ChatFullView} />
      </Switch>
    </BrowserRouter>
  </Provider>
);

render(component, container);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM