Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Router param types #47

Merged
merged 4 commits into from
Jan 18, 2020
Merged

Feature: Router param types #47

merged 4 commits into from
Jan 18, 2020

Conversation

mojombo
Copy link
Contributor

@mojombo mojombo commented Jan 17, 2020

Want to constrain a route param to look like a number and then auto-convert it into an actual JS number before passing it on? BOOM:

<Route path="/order/{num:Int}" page={OrderPage} name="order" />

// Given path `/order/3` the params would be `{ num: 3 }`
// Notice that 3 is an integer, not a string!

The above is actually shorthand for doing it the long way:

<Route
  path="/order/{num}"
  page={OrderPage}
  name="order"
  constraints={{ num: /\d+/ }}
  transforms={{ num: parseInt }}
/>

That's cool and all, but what if you have your own constraints and transforms that you want to apply in multiple routes? Oh, Redwood can do that:

const paramTypes = {
  slug: {
    constraint: /\w+-\w+/,
    transform: (x) => x.split('-'),
  },
}

const Routes = () => {
  return (
    <Router paramTypes={paramTypes}>
      <Route path="/post/{id:slug}" page={PostPage} name="post" />
      <Route notfound page={NotFoundPage} />
    </Router>
  )
}

// Given path `/post/super-duper` the params would be `{ id: ['super', 'duper'] }`

Core param types like Int start with an uppercase letter, and user param types start with a lowercase letter. This means we can add core types without ever conflicting with anyone's user types. Tada!

@mojombo mojombo requested a review from peterp January 18, 2020 06:23
Copy link
Contributor

@peterp peterp left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Awesome!

@mojombo
Copy link
Contributor Author

mojombo commented Jan 18, 2020

This PR doesn't yet handle the per-route constraints and transforms but I'm going to save that for a later PR so we can get the tutorial functionality working right away.

@mojombo mojombo merged commit 53271f8 into master Jan 18, 2020
mohsen1 pushed a commit to mohsen1/redwood that referenced this pull request Apr 12, 2020
@thedavidprice thedavidprice deleted the tpw-router-param-types branch June 9, 2020 23:03
@thedavidprice thedavidprice added this to the unassigned-version milestone May 14, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants