简体   繁体   中英

How do I render a React component into the main App component/

I'm in the process of moving my client-side code from jQuery to React. My (trimmed) main app looks like this

export const MyApp: FC = () => {
return <HashRouter>
    <SideNav {...data} />
    <Switch>
        <Route exact path="/" component={Dashboard} />
    </Switch>
</HashRouter>
}

And inside several components I sometimes need to call functions that build React components. Such as

export async function openDialog(recordId?: number) {
const elem = document.createElement('div');
elem.style.display = 'contents';
ReactDOM.render(<ConfigProvider>
    <Modal
        visible recordId={recordId} 
        onCancel={() => {
            ReactDOM.unmountComponentAtNode(elem);
            document.body.removeChild(elem);
        }} 
    />
</ConfigProvider>, elem);
document.body.appendChild(elem);
}

Problem is, that if in my Modal I have a react-router Link , then I get the following error:

Uncaught Error: Invariant failed You should not use Link outside a Router

Now, I could understand the error, because I'm rendering outside the context of the MyApp . My question is: How can I change my function so it does render into the same context of MyApp ?

I was not able to find any such question or concept online (aside of rewriting my whole app to use a state for each window I need to open, which is not practical at the moment).

Thanks!

The components which use router links must be children of components rendered inside a router.

In your case, you only have <Dashboard /> and <SideNav /> rendered inside your router. Make sure that <Modal / > is rendered by <Dashboard /> , <SideNav /> , or a descendant of them.

You also manipulate DOM elements directly and this is not good practice with React. You could run into confusing bugs as React will not recognize changes to the DOM

See: https://reactjs.org/docs/integrating-with-other-libraries.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM