React - How to route parent div from child div

I'm attempting to route the main app from a selection in one of its children's children's components. My project is structured like this:

        <Link to={"/home}>Home</Link>
        <Link to={"/search}>Search</Link>

        <Route exact path="/" component={Home}
        <Route exact path="/search" component={Search} />

    <Messages and stuff>
    <List />

<List> => (

<View> about thing ...

My goal is to be able to click on a specific button inside List and have Main reroute from site/ to site/view{id}, similar to the way clicking on "search" in Main would route to site/search. I don't want to have View be inside Home or List, I want it to be a child of Main. How would I go about this? Passing a function that manually switches? Linking something somewhere? I'm relatively new to React and routers, but I didn't find anything from when I looked through the docs.

2 answers

  • answered 2019-03-13 18:08 Joshua Underwood


    You would need a route that looks something like this...

    <Route path="/view/:id" component={View} />

    and a Link like

    <Link to=/view/${}>Click me!</Link>

    Note the :id which denotes that there is a variable after the view/

    Then in your View component you'll access the ID via this.props.location

    If you'd rather pass the entire list item and not just the ID (because the data isn't accessible from the View component for whatever reason) you can also send the entire item like so

    <Link to={{ pathname: '/view', state: thing }}>Click Me!</Link>

    Then in the view component look at this.props.location.state

    Also just a heads up, you don't need exact in a route unless you plan to have things after the trailing slash.

    For example...

    route="/" Needs exact

    route="/item" Does not need exact

    route="/season" Needs exact cause it has subroutes (spring)

    route="/season/spring" Does not need exact because it has no further subroutes

  • answered 2019-03-13 18:16 Dwarka Tiwari

    There are two ways to do it

    1. To pass a function from main to child as props to retrieve id of clicked and load view data accordingly

    2. Hence you are using react router you could add one more route

    Look at below example link for more details