Home > Blockchain >  Listening to component's state change from different component using React Router v6
Listening to component's state change from different component using React Router v6

Time:02-06

I have a Page component that is rendered within App using </Outlet>. Within the Page component I would like to use a state (a simple text provided via search input) which is set in App.

I was able to send and receive the state during Page mounting via navigate("/page", { state: { searchQuery } }); executed from App, but unfortunately this approach failed when the state of searchQuery changed.

Is there a simple mechanism which will allow Page to listen to the changes of App selectQuery state in React Router v6 and if so what's the solution?

// index.tsx
const router = createBrowserRouter(
  createRoutesFromElements(
    <Route path="/" element={<App />}>
      <Route path="page" element={<Page />}></Route>
    </Route>
  )
);
// App.tsx 
function App() {
  const [searchQuery, setSearchQuery] = useState<string>("");

  return (
    // ...
    <AppBar component="nav">
      // Input text field which sets setSearchQuery onChange
    </AppBar>
    // ...
      <Outlet />
    // ...
}
// Page.tsx
function Page() {
  //...
  return (
    // ...
    // usage of a App searchQuery 
    // ...
}

CodePudding user response:

You can do that using outlet context:

function App() {
  const [searchQuery, setSearchQuery] = useState<string>("");

  return (
    // ...
    <AppBar component="nav">
      // Input text field which sets setSearchQuery onChange
    </AppBar>
    // ...
      <Outlet context={searchQuery}>
    // ...
  )
}
import { useOutletContext } from 'react-router-dom';

function Page() {
  const searchQuery = useOutletContext();

  return (
    // ...
    // usage of a App searchQuery 
    // ...
  )
}

For more information, see this documentation: https://reactrouter.com/en/6.8.0/hooks/use-outlet-context

  • Related