First, create an index.html file where the React application will be rendered, containing as well an HTML header tag where a React portal element will be rendered:
- Create a new file named index.html
- Add the following HTML code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Portals</title> </head> <body> <header id="heading"></header> <div role="main"></div> <script src="./portals.js"></script> </body> </html>
- Save the file
Next, build a React application that will render a paragraph and an h1 HTML element outside of the tree to a header HTML element:
- Create a new file named portals.js.
- Import the React and ReactDOM libraries:
import * as React from 'react' import * as ReactDOM from 'react-dom'
- Define a functional component named Header and create a portal to render the children to a different DOM element:
const Header = () => ReactDOM.createPortal( <h1>React Portals</h1>, document.querySelector('[id="heading"]'), )
- Define a functional component named App that will render a React element and the Header React component:
const App = () => ( <React.Fragment> <p>Hello World!</p> <Header /> </React.Fragment> )
- Render the application:
ReactDOM.render( <App />, document.querySelector('[role="main"]'), )
- Save the file.