Roi
Roi

Reputation: 1003

React router v4 - Rendering two components on same route

I have these routes

 <Route exact path={`/admin/caters/:id`} component={Cater} />
 <Route exact path={'/admin/caters/create'} component={CreateCater} />

When I navigate to the first route I get a cater with a given ID. And the Cater component is rendered

When I navigate to the second route, the CreateCater component is rendered on the page, but I noticed that some redux actions that are used in the Cater component are being run. So both component are somehow being rendered - but I can't figure out why.

Here are the components:

Cater:

class Cater extends Component {

  async componentDidMount() {
        console.log('Cater component did mount')
        const { match: { params: { id }}} = this.props
        this.props.get(id)
    }

    render() {
        const { cater } = this.props
        if(!cater) {
            return null
        }
        else {
            return (
                <div>
                   ... component data ...
                </div>
            )
        }
    }
}

const mapStateToProps = (state, props) => {
    const { match: { params: { id }}} = props
    return {
        cater: caterSelectors.get(state, id)
    }
}

const mapDispatchToProps = (dispatch, props) => {
    return {
        get: (id) => dispatch(caterActions.get(id))
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Cater)

CreateCater:

export default class CreateCaterPage extends Component {
    render() {
        return (
            <React.Fragment>
                <Breadcrumbs />
                <CaterForm />
            </React.Fragment>
        )
    }
}

When I go to /admin/caters/create' I can see the console.log in the componenDidMount() lifecycle method inside the Cater component.

I cant figure out what I am doing wrong :(

Upvotes: 3

Views: 2723

Answers (2)

Blue
Blue

Reputation: 22921

/create matches /:id, so it makes sense that this route matches. I recommend forcing :id to look for numeric only:

<Route exact path={`/admin/caters/:id(\\d+)`} component={Cater} />
<Route exact path={'/admin/caters/create'} component={CreateCater} />

Likewise, you can follow @jabsatz's recommendation, use a switch, and have it match the first route that matches. In this case, you would need to ensure that the /admin/caters/create route is the first <Route /> element matched.

Upvotes: 7

jabsatz
jabsatz

Reputation: 351

The problem is that :id is matching with create (so, it thinks "see cater with id create"). The way to solve this is to put the wildcard matching route last, and wrapping all the <Routes/> with a <Switch/>, so it only renders the first hit.

Check out the docs if you have any more questions: https://reacttraining.com/react-router/core/api/Switch

Upvotes: 1

Related Questions