0

In React-Router 4 I am configuring the basename like so:

<BrowserRouter basename="/aaaa/bbbb/*/cccc">

Where * can be any integer. However this isn't working - is my syntax wrong?

GluePear
  • 7,244
  • 20
  • 67
  • 120

1 Answers1

0

You can create an array or something that allows you to dynamically create the link and route elements:

// create the array with the ids and the components
const wildcards = [
  {id: 0, target: ComponentOne},
  {id: 1, target: ComponentTwo},
  {id: 2, target: ComponentThree}
];

// now map to create the links
{wildcards.map( e => {
  return <Link className="btn btn-secondary" to={`/aaa/bbb/${e.id}/ccc`}>Component {e.id}</Link>
})}

// then the routes
{ wildcards.map( e => {
  return <Route path={`/aaa/bbb/${e.id}/ccc`} component={e.target} key={`component_${e.id}`}></Route>
})}

Here's a live sample of this approach:

https://codesandbox.io/s/vyO05x2g

Also React Router offers using a colon inside the Route element. Although this approach will render the same base component and in that one you should create your logic to render the specific data for that particular path:

<Route path="/aaa/bbb/:id/ccc" component={MyBaseComponent}></Route>

// then in the base component
const MyBaseComponent = ({match}) => {
  // run your logic here
  return(
    <div>Your content depending on the match params</div>
  );
};

EDIT

Based on the comment, we weren't on the same page. I'm assuming that you want to pass a different value depending on what your code does. In that case you can use template literals to pass a variable, prop or state property to the base router: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Like this:

<BrowserRouter basename=`/aaaa/bbbb/${wildcard}/cccc`>

That should pass whatever wildcard is on each render of the component that has the <BrowserRouter /> on it.

Rodrigo
  • 1,638
  • 1
  • 15
  • 27
  • Thanks - but my question was about whether I can use a wildcard in the `basename` attribute. – GluePear Jul 27 '17 at 15:09
  • I believe you can use a wildcard by matching the part of your string that changes in parentheses () and using regex, i.e. "aaaa/bbbb/(*)/cccc" – redconservatory Jul 29 '17 at 13:22