I am using react-router v4.2.2 and am trying to use a function to spit out a list of routes with a component property value of "project.title", taken from a reducer I am using. However, when I write:
return <Route key={i} exact path={`/${project.title}`} exact component={project.title}/>
using the project.title part results in this error:
Failed prop type: Invalid prop
componentof typestringsupplied toRoute, expectedfunction.
but when I replace project.title with an actual component like Project1:
return <Route key={i} exact path={`/${project.title}`} exact component={Project1}/>
then it's fine.
Is there a way I can use the titles of each project, from my reducer, in this function, without this error popping up?
here is the whole container code, in case it's helpful:
import React from 'react';
import Project1 from '../components/project1.js';
import { connect } from 'react-redux';
import { Route, Switch } from 'react-router-dom';
import { withRouter } from 'react-router';
import ProjectCards from '../containers/project_cards.js';
class App extends React.Component{
render() {
var createRoutes = this.props.projects.map((project, i) => {
return <Route key={i} exact path={`/${project.title}`} exact component={project.title}/>
});
return (
<Switch>
<Route exact path="/" component={ProjectCards}/>
{createRoutes}
</Switch>
);
}
}
function mapStateToProps(state) {
return {
projects: state.projects
};
}
export default withRouter(connect(mapStateToProps)(App));
You can't just pass a string as the component if a route -- it expects an actual component. What I would recommend is saving all your components in some kind object which then you can access:
const projects = {
Project1,
…
};
…
<Route key={i} exact path={`/${project.title}`} exact component={projects[project.title]}/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With