js_248
js_248

Reputation: 2112

Route matching in React

I want to make a page with url users/:userId where userId will be (java, cpp, c).So in home page if click on java button it will open a page wit url users/java, similarly for c and cpp.All these pages will have same layout with different data.For this I made a simple component as Lang.jsx

export class Lang extends Component{
  render() {
  const { data } = this.props;
    return (
      <div>
       <h1>{data.lang}</h1>
      </div>);
  }
}

In Router class we have to write something as

<Route path="users/:userId" component={Lang} />

But it is not clear how to pass userId in router and load Lang for each url?

Upvotes: 1

Views: 667

Answers (2)

Mayank Shukla
Mayank Shukla

Reputation: 104359

Use Link for these java, cpp, c, like this:

<Link to='users/java'>Java</Link>
<Link to='users/cpp'>Cpp</Link>
<Link to='users/c'>C</Link>

If you are using history.push() then write it like this:

hashHistory.push('users/java');

Note: You can make that userid optional because if you don't pass userid it will not match to any route, write it like this to make it optional:

<Route path="users/(:userId)" component={Lang} />

Now if you don't pass anything then also it will open the Lang page.

One more thing since you are passing the parameter by name userId, so it will available by this.props.params.userId not by this.props.data.lang.

Upvotes: 1

David
David

Reputation: 1356

I'm not completely sure what you're trying to do here, but if you have a look at this.props inside of lang, there will be a params key (this.props.params), which will be an object containing the userId.

eg:

this.props = {
  params: {
    userId: '1234',
  },
}

This means that when you go to /user/1234, the userId key will have the value of 1234.

I'm not really sure what you're expecting the value of data.lang to be. Are you wrapping the routes in another route that provides that prop? What library are you using for lang?

Upvotes: 0

Related Questions