I have a component that contains react-router-dom's Link but throws the error below when I pass the component in the react-dom renderToString
Uncaught Error: useHref() may be used only in the context of a <Router> component.
Can't I pass a component that has react hooks into renderToString functions?
import { renderToString } from 'react-dom/server';
const html = renderToString(<Contact />);
console.log(html);
I guess you use the
useHref()hook inside<Contact/>component. ButuseHref()hook must be used in a Router context, the error throws at line lib/hooks.tsx#L36. Let's see the source code ofuseHref()hook:We can use
<StaticRouter>to do the SSR,StaticRoutercomponent uses Router component underly,Routeruses NavigationContext.Provider and LocationContext.Provider components to provide the context value to its children components, then you can useuseHref()hook in these children components.Here is a working example:
Test result:
package version: