I am using a combination of react-router-dom
and Material-UI
in my app. I’ve tried to make a very basic example below with the following files:
routes.tsx
import { Outlet, createBrowserRouter } from "react-router-dom"
const App = () => {
return (
<BaseLayout>
<Outlet />
</BaseLayout>
)
}
export const router = createBrowserRouter([
{
path: "/",
element: <App />,
children: [
{ index: true, element: <Home /> },
],
},
])
BaseLayout.tsx
export const BaseLayout = {children} => {
return (
<>
<head />
<main>{children}</main>
<footer />
<Alert />
</>
)
}
Home.tsx
export const Home = () => (
<>
<button /> // <-- I want this button to trigger the Alert and set open to true !
</>
)
Alert.tsx
import { Alert as MuiAlert, Snackbar } from "@mui/material"
export const Alert = ({open?, severity?, message?}) => {
return (
<Snackbar
open={open}
autoHideDuration={500}
// onClose={handleClose}
// action={action}
>
<MuiAlert severity={severity}>{message}</MuiAlert>
</Snackbar>
)
})
I am trying to have a single Alert
component shared across the application that can trigger an alert for different reasons.
I am not sure how to approach it.
3
Answers
you just import your Alert component in any other components in which you may show the Alert. in the parent component you have to create a state to control the alert visibility:
finally to show the Alert component, all you have to do is to set
isAlertOpen
totrue
:I would suggest keeping some state in the
BaseLayout
component for the open/close status of the alert, and move theOutlet
intoBaseLayout
and provide this state and setter on the outlet’s context provider. TheHome
component would use theuseOutletContext
hook to access the provided context value.I think you should use Context.
You can read more at https://react.dev/reference/react/useContext
For example you can create a alterProvider and in that file will there
or you just can use any globle client state managerment like Redux or Mobx.