g3blv
g3blv

Reputation: 4377

React Router v4 params

I'm following a React tutorial that is using React Router v3. While I'm using React Router v4. I'm passing a parameter called id from a component called Root to another component called User.

export class Root extends  React.Component {
    render() {
        return(
            <div className="container">
                <div className="row">
                    <div className="col-xs-10 col-xs-offset-1">
                        <Header />
                    </div>
                </div>
                <div className="row">
                    <div className="col-xs-10 col-xs-offset-1">
                        <hr/>
                        <Route exact path="/" component={Home}/>
                        <Route path="/user/:id" component={User}/>
                        <Route path="/home" component={Home}/>
                        {/*{this.props.children}*/}
                    </div>
                </div>
            </div>
        );
    }
}

And I'm picking up the parameter with {this.props.match.params.id} like below and works.

export class User extends React.Component {

    onNavigateHome() {
        this.props.history.push("/home")
    }

    render() {
        return (
            <div>
                <h3>The User Page</h3>
                <p>User ID: {this.props.match.params.id}</p>
                <button onClick={() => this.onNavigateHome()} className="btn btn-primary">Go home!</button>
            </div>
        );
    }
}

In the tutorial {this.props.params.id} is used. Am I doing it the right way in with {this.props.match.params.id}? And what does match mean?

Upvotes: 3

Views: 1060

Answers (1)

Davorin Ruševljan
Davorin Ruševljan

Reputation: 4392

Match is property that react router v4 injects when the route’s path matches.

A match object has following properties:

  • url —the matched part of the current location’s pathname
  • path — the route’s path
  • isExact—path === pathname
  • params — an object containing values from the pathname that were captured by path-to-regexp

As for following V3 tutorial with V4 - I would not recommend it since there are substantial changes between two versions

Upvotes: 1

Related Questions