How to do it...

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:

  1. Create a new file named index.html
  2. 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> 
  1. 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:

  1. Create a new file named portals.js.
  2. Import the React and ReactDOM libraries:
      import * as React from 'react' 
      import * as ReactDOM from 'react-dom' 
  1. 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"]'), 
      ) 
  1. 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> 
      ) 
  1. Render the application:
      ReactDOM.render( 
          <App />, 
          document.querySelector('[role="main"]'), 
      ) 
  1. Save the file.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.172.82