Answer the question
In order to leave comments, you need to log in
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>,
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)
);
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question