12

How can I check for empty state and redirect to the first route, if needed?

I have my routes.js

export default (
    <Route path="/" component={App}>
        <IndexRoute component={Screen1} />
        <Route path="/1" component={Screen1} />;
        <Route path="/2" component={Screen2} />
        <Route path="/3" component={Screen3} />
        <Route path="/4" component={Screen4} />
        <Route path="/5" component={Screen5} />
        <Route path="/6" component={Screen6} />
    </Route>
);

and my index.js

const store = configureStore();
console.log({ store });
render(
    <Provider store={store}>
        <Router history={browserHistory} routes={routes} />
    </Provider>,
    document.getElementById('root')
);

How would I do that using react-router

app.js

import React, { PropTypes } from 'react';
import Header from './common/Header';
import ModalRoot from './modals/Modal';
import Footer from './common/Footer';
class App extends React.Component {
    render() {
        return (
            <div className="container-fluid">
                <ModalRoot />
                <Header />
                {this.props.children}
                <Footer />
            </div>
        );
    }
}

App.propTypes = {
    children: PropTypes.object.isRequired,
};

export default App;
Bomber
  • 10,195
  • 24
  • 90
  • 167

1 Answers1

3

Here's a snippet using React-router-dom@4.0

import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom';

const Wildcard = () => {
  <Redirect to="/" />
};

const store = configureStore();
console.log({ store });
render(
    <Provider store={store}>
        <Switch>
          <Route exact path="/" component={YOURCOMPONENT} />
          <Route exact path="/:section/:news/:title" component={App} />
          <Route exact path="/:section/:sector/:news/:title" component={App} />
          <Route exact path="/*" component={Wildcard} />
        </Switch>
    </Provider>,
    document.getElementById('root')
)

In the first Route insert your component name that represents your 'index'. Update your file index.js

I've inserted another 2 routes below the YOURCOMPONENT path just to make this example look more real, but it's optional.

Yuri Pereira
  • 1,945
  • 17
  • 24
  • I tried it but it shows me an error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. – saeta Dec 13 '17 at 17:15