I'm designing a MFE app called header. Implementation is something like below,
header.js
const headerApp = () => {
const navigate = useNavigate();
const logoClickHandler = () => {
navigate('/some-route'); // router v6
}
return(
...
<Logo onClick={logoClickHandler} />
)
}
App.js
I want to keep/use it like below
const App = () = {
return(
<div>
<HeaderApp /> // This component just uses useNavigation or <NavLink to='/some-route' />
</div
)
}
Problem is Header app doesn't have its own routing mechanism in it. It is just a separate app and to be more specific standalone component and just provides navigations among different MFE apps using useNavigate()
OR <NavLink />
router feature.
Since, I'm using useNaviage()
OR <NavLink />
, react is asking me to wrap the component inside <Routes>
(as shown below) which is unnecessary for my header app.
React Error
useNavigate() may be used only in the context of a
<Router>
component.
don't want to end up like below,
const App = () = {
return(
<div>
<Routes>
<Route path='/' element={ <HeaderApp /> } />
</Routes>
</div
)
}
NOTE : Routing is handled in separate app called container. Header only provides links for navigations.
CodePudding user response:
React Router uses React Context, which is a way of passing information down through the React tree. Because of this, you only need to make sure you have at least one <Router>
as a parent of whatever component is rendering <headerApp />
for this to work.
If this is not acceptable to you - you want your application to be used in non-React router contexts, for example - you may want to refactor your header application such that it either provides its own React Router instance or accepts the required methods and attributes through props.
It is not possible to use <NavLink />
or useNavigate()
without one of the parents of <headerApp />
using Router />
.