Michel H.
Michel H.

Reputation: 300

Global popup in React with Router and Redux

I implemented a well working view layer in React JS where everything still operates on dummy data.

Now I need a modal popup that can be triggered from a lot of different components. According to this thread this could be nicely implemented with Redux, so I tried that.

After having to change my Router and reading countless docs I came up with

const Root = ({store}) => (
    <Provider store={store}>
        <Router history={browserHistory}>
            <Route path="/" component={...}/>

            <Popup visible={store.getState().taskEditPopup.open}>
                <...>
            </Popup>
        </Router>
    </Provider>
)


ReactDOM.render(
    <Root store={store}/>,
    document.getElementById('react')
)

When the Popup is a child of Provider, it gives an error and as a child of Router it does not appear in the DOM.

So where to put this global modal? Is there a standard way to solve this?

Upvotes: 0

Views: 1658

Answers (1)

adrice727
adrice727

Reputation: 1492

It think it's fairly common to use a top-level component (App) to nest things like headers/footers, global popups, etc. You can then nest the rest of your routes inside App.

Routes example:

const routes = (
  <Router history={browserHistory}>
    <Route path="/" component={App} >
      <IndexRedirect to="login" />
      <Route path="login" component={Login} />
      <Route path="/home" component={Home} />
    </Route>
  </Router>);

Then within App.js:

import MyPopup from '../Popup/Popup';

const App = ({ children }) =>
  (<div className="App">
    <MyPopup />
    { children }
  </div>);

export default App;

And then you can connect MyPopup and pass it props from redux.

Upvotes: 2

Related Questions