React-router: Pass parameters through Link

Created on 23 Mar 2015  路  4Comments  路  Source: ReactTraining/react-router

As in example dynamic-segments:

var routes = (
  <Route path="/" handler={App}>
    <Route name="user" path="/user/:userId" handler={User}>
      <Route name="task" path="tasks/:taskId" handler={Task}/>
      <Redirect from="todos/:taskId" to="task"/>
    </Route>
  </Route>
);
...
var User = React.createClass({
...
  render () {
...
          <li><Link to="task" params={{userId: userId, taskId: "foo"}}>foo task</Link></li>
          <li><Link to="task" params={{userId: userId, taskId: "bar"}}>bar task</Link></li>
...
});

But I want to use Route "task" without :taskId:

<Route name="task" path="tasks" handler={Task}/>

Is it possible to pass a parameter taskId to Task from Link, without specifying it in the path in Route? I don't want use the query for this. If I specify taskId in params, query or simply specify as different parameter in Link, I cannot get it in Task.

Most helpful comment

Can have the parameter be optional

<Route name="task" path="/task/?:taskId?" handler={Task}>

All 4 comments

I solved the problem as follows:

var User = React.createClass({
    taskId: "",
    ...
    handleClick: function(task) {
        var that = this;
        return function(event) {//without return event will bubble to default handler (?)
            that.taskId = task;
            console.log("set taskId: " + that.taskId);
        }
    },
    render: function() {
        console.log("verify taskId: " + this.taskId);
        return dom.div(...
            Link({to: "task", params: {userId: params.userId}, onClick: this.handleClick("foo")}, "foo task")
            ...
            RouteHandler({taskId: this.taskId})
            ...
    });
...
var Task = React.createClass({
    ...
    render: function() {
        console.log("get taskId: " + this.props.taskId);
    ...

Running ... click on link, in console:

set taskId: foo
verify taskId: foo
get taskId: foo

It's works. But all of this implementation is similar to cheap craft (((
Did I surely miss something?

Can have the parameter be optional

<Route name="task" path="/task/?:taskId?" handler={Task}>

A little late answer but what you are after is really
<Route name="task" path="/task/(:taskId)" handler={Task}>
which makes taskId optional

Was this page helpful?
0 / 5 - 0 ratings