16

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;
0

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.