I have my component for notification
For now this component is only visible in my home page. What I need? I need to be visible in every route, example if I want to change route to be visible in different route, where to put this component?
Right now this is inside Home page and will be triggered in some case. Work good but when. go to different page is not visible..
Where to set this component to be visible in every page? I am try inside
const root = document.createElement('div');
document.body.appendChild(root);
render(
<StrictMode>
<NotificationComponent />
<App />
</StrictMode>,
root,
);
but this is not solution....
CodePudding user response:
if you want your notification component to visible in every page, use it or import it in your APP.js
CodePudding user response:
Using Context API, wrap the App
with the provider and pass the visibility setter to its children, from there you can update the notification state from any of the provider's children.
Notificationprovider
import { render } from 'less'
import React, { createContext, useState } from 'react'
export const NotificationCtx = createContext()
function NotificationProvider({ children }) {
const [isVisible, setIsVisible] = useState(false)
return <NotificationCtx.Provider value={{ setIsVisible }}>
{children}
{isVisible && <div>Notification</div>}
</NotificationCtx.Provider>
}
index
render(
<NotificationProvider>
<App />
</NotificationProvider>, root
)
App
import { useContext } from 'react'
import { NotificationCtx } from "yourpath/to/provider"
function App() {
const { setIsVisible } = useContext(NotificationCtx)
return <button onClick={() => setIsVisible(true)}></button>
}
You can access the setIsVisible
from App's children using useContext.