0

I am currently looking into React.js & Redux and was playing around with react-router. My question is: Is there a way to access url params from another Component?

For example:

I have a Foo component which displays the :bar param (via props.match.params.bar), but I also want to display the value of :bar in the Header Component. With ReactRouterDOM.withRouter I can get access to props.match. The Problem is that this is not the same as in the Foo Component (it contains the information about the parent route '/'). So how do I get the value in the Header Component and am I even on the right track?

Thanks in advance

const Foo = (props) => {
    return (<div> <h1> Foo {props.match.params.bar} </h1> </div>);
};

const App = (props) => {
    return (
        <div>
            <HeaderWrapper />
            <h1> Hello App </h1>
            <p><ReactRouterDOM.Link to='/foo/bar'>Foo Bar</ReactRouterDOM.Link></p>
            <hr />
        
            <ReactRouterDOM.Route path='/foo/:bar' component={Foo} />
        </div>);
};

// Header
const Header = (props) => {
    console.log(props);
    return ( <header> <small>You are here: {}</small>  </header>);
};
const HeaderWrapper = ReactRouterDOM.withRouter(Header);

// Router
ReactDOM.render((
        <ReactRouterDOM.MemoryRouter>
            <ReactRouterDOM.Route path='/' component={App} />
        </ReactRouterDOM.MemoryRouter >
 ), document.getElementById('root'));
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.min.js"></script>
<script src="https://unpkg.com/react-router-dom/umd/react-router-dom.min.js"></script>

1 Answer 1

2

As far as I know, react-router doesn't have any standard way to achieve what you need. But you can use regular expression with path-to-regexp library to do that manually. You will always get the correct result as react-router it self internally use this library to match routes.

const re = pathToRegexp('/foo/:bar')
const result = re.exec(props.location.pathname)
if(result){
    console.log(result[1]); //bar
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.