Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router v4.2.2: using a string instead of function inside component prop of Route results in error

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 component of type string supplied to Route, expected function.

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));
like image 343
user74843 Avatar asked Nov 25 '25 12:11

user74843


1 Answers

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]}/>
like image 141
Andrew Li Avatar answered Nov 27 '25 00:11

Andrew Li



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!