0

Being pretty new to React, I'm facing an issue with navigating between 2 components.

My app is as follows: App.js:

 <div className="App">

      <AuthProvider>
        <ThemeProvider theme={theme}>
          <CssBaseline />
          <CartProvider>
            <SiteHeader/>

            <div>
              <Routes>
                {getRoutes(routes)}
                <Route path="/auth" element={<AuthPage />} />
                <Route path="/cart" element={<CartPage />} />
                <Route path="/search_results" element={<SearchResultPage />} />
                <Route exact path="/_healthz" element={<HealthPage />} />
                <Route path="/orders" element={<OrderPage />} />
                <Route path="/category/:id" element={<CategoryPage />} />
                <Route path="/product/:id" element={<ProductPage />} />
                <Route path="/recipe/:id" element={<RecipePage />} />
                <Route path="/" element={<HomePage />} />
              </Routes>
            </div>

          </CartProvider>
        </ThemeProvider>
      </AuthProvider>

    </div>

As you can see, there is the SiteHeader component on every page. On this SiteHeader Component, I have a search field, triggering a navigate() to SearchResultPage Although the navigation itself is working (SearchResultPage is displaying), the parameters passed to navigate() are not propagated:

  const search = () => {
    console.log("Calling search =>" + searchTerm);
    navigate("/search_results",{ state: { searchText: searchTerm }});
  }

Below the code part for SearchResultPage:

export default function SearchResultPage(props) {
  console.log(props);
  let searchText = props.location.searchText

I don't understand why props is empty although I populated the navigate(path,state) correctly

Sebastian
  • 5
  • 5

2 Answers2

2

react-router-dom v6 Route components rendered via the element prop don't receive route props.

You can use hook for getting the state given you are navigating to that page by passing some state value as follows:

const location = useLocation();
const searchText = location?.state?.searchText;

For getting state you need to access props.location.state and then subsequent state property if you are using v5 or below.

GodWin1100
  • 1,380
  • 1
  • 6
  • 14
  • thanks @GodWin, this worked and made my day. Any idea why the props did not propagate ? – Sebastian Jul 07 '22 at 12:22
  • Because `` components rendered via `element` i.e. `}/>` don't receive any props of `route props` such as search, location, param, etc. In short, props are not passed in **V6** – GodWin1100 Jul 07 '22 at 12:54
  • @Sebastian There are not any route props in RRDv6, the `Route` component API changed significantly. Use the React hooks in the routed component. – Drew Reese Jul 07 '22 at 15:39
0

Change this line:

let searchText = props.location.searchText

to

let searchText = props.location.state.searchText
User456
  • 1,216
  • 4
  • 15