hotshotiguana hotshotiguana - 3 months ago 27
React JSX Question

react-router <Link/> Wildcard Path Matching

In my application, I have a

<NavBar/>
component with a few links which tell the back-end to return a random
location_id
in the specified State. This works well, but because I
browserHistory.replace()
the
random
path with the returned
location_id
path the
<NavLink/>
no longer matches the router path and therefore doesn't remain
active
. Is there a way to make the
<Link/>
component match for every
location_id
including
random
, i.e. a
MA
link would remain active if the url were
/locations/MA/1
,
/locations/MA/random
, or more generally
/locations/MA/*
. but continue to point to
locations/MA/random
?

/* ./modules/NavLink.js */
import React from 'react'
import { Link } from 'react-router'

export default React.createClass({
render() {
return <Link {...this.props} activeClassName="active"/>
}
})

/* Main use of the <NavLink/> */
<NavLink to="/locations/MA/random">Massachusetts</NavLink>

Answer

One way to do it is configure the 'to' attribute of component to "/locations/MA" so that it remains active for all "/locations/MA/*". But bind it to a 'onClick' function like this

    const onLinkClick = (evt) => {
      evt.preventDefault()
      history.push('locations/MA/random')
    }

Now although it remains active for all matches, it will only navigate to one URL

Comments