N
N
Nikita Shchypylov2018-03-07 23:23:39
React
Nikita Shchypylov, 2018-03-07 23:23:39

How to dynamically add Routes in React?

Hello everyone
I have added news and want to add a new Route. Now I did this, but it does not work :
index.js :

<Provider store={store}>
      <Router history={history}>
        <App/>
      </Router>
    </Provider>,

app.js :
import React, { Component } from "react";
import { Switch, Route, withRouter } from "react-router-dom";
import { fetchStories } from "../ac";
import Header from "./Header/index";
import Dashboard from "./Dashboard/index";
import { connect } from "react-redux";

class App extends Component {
  componentWillMount() {
    this.props.fetchStories();
  }
  render() {
    let { stories } = this.props;
    const routes = stories ? (
      Object.keys(stories).map(element => {
        let url = stories[element].title;
        console.log(url);
        return (
          <Route
            key={stories[element].title}
            path={url}
            render={() => (
              <div className="app">
                <Header />
                <div>new</div>
              </div>
            )}
          />
        );
      })
    ) : (
      <div>loading</div>
    );
    return (
      <Switch>
        <Route
          path="/"
          exact
          render={() => (
            <div className="app">
              <Header />
              <Dashboard stories={this.props.stories} />
            </div>
          )}
        />
        {/* <Route /> */}
        {routes}
      </Switch>
    );
  }
}

const mapDispatchToProps = {
  fetchStories
};

export default withRouter(
  connect(
    state => ({
      stories: state.stories
    }),
    mapDispatchToProps
  )(App)
);

When I click on the url, I get a white screen

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-03-07
@Nikulio

Use route  with the parameter: where slug is the field of the news entry in the database, based on its name. Learn more about slug.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question