简体   繁体   中英

How can I create a new portal in react js?

I'm trying to create a new portal with an id.

This is the index html file in the public folder:

 <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <div id="other"></div>
  </body>

And here I tell react to render this component inside the div with the id of root:

import React from 'react';
import ReactDOM from 'react-dom';

function New() {
    return ReactDOM.createPortal(<h1>DEMO</h1>, document.getElementById('other'));
}

export default New;

But when I npm start I dont see anything inside the div with the id of other.

How can I create a new portal in react js properly?

I solved the problem by including the New component inside App.js file:

import React from 'react';
import logo from './logo.svg';
import './App.css';

import New from './New';

function App() {
    return (
        <div className="App">
            <New />
        </div>
    );
}

export default App;

And when I inspect it, the New component is actually inside the div with the id of other.

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