[React] React Router: Route Parameters

A router library is no good if we have to hardcode every single route in our application. In this lesson we look at how to access variables in our routes and pass them into our components.

 

Define a route param by using “:message”, () make it optional:

<Route path="/(:message)" component={Home}></Route>

 

Get route param:

const Home = (props) => <div><h1>{props.params.message ||'hello'}</h1><Links></Links></div>;

 

—————

 

import React from 'react';
import {hashHistory, Route, Router, Link, IndexRoute} from 'react-router';

const Home = (props) => <div><h1>{props.params.message ||'hello'}</h1><Links></Links></div>;

const Links = () =>
    <nav >
        <Link to="/">Home</Link>
        <Link to="/foo">Foo</Link>
        <Link to="/bar">Bar</Link>
    </nav>;

class App extends React.Component {
    render(){
        return(
            <Router history={hashHistory}>
                <Route path="/(:message)" component={Home}></Route>
            </Router>
        );
    }
}

export default App;

 

Related Posts

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注