DEV Community

loading...
Cover image for ⚛️ Initiate a React app with multiple components on a single DOM element
Visual Composer

⚛️ Initiate a React app with multiple components on a single DOM element

nikitahl profile image Nikita Hlopov ・2 min read

In this article, I'll go through the use case of rendering multiple React components to a single DOM element of a React app.

There might be a case when your app consists of independent components that might need to be initiated from different places on different conditions but inside a single container.

Turns out that React can handle these cases with ease.

  1. Initiate a generic React app
  2. Initiate a React app with multiple components

Initiate a generic React app

Usually, the generic React app begins like so:

HTML have a single div container element:

<div id="app"></div>

The React part is a single component that gets rendered inside a given DOM container:

const appContainer = document.getElementById('app')

function Form () {
  const handleSubmit = (e) => {
    e.preventDefault()
  }
  return (<form onSubmit={handleSubmit}>
    <input type="email" placeholder="email@example.com" />
    <input type="submit" value="Submit" />
  </form>)
}

ReactDOM.render(<Form />, appContainer)

Initiate a React app with multiple components

To initiate your app with multiple components you need to wrap them in a React Fragment inside the ReactDOM.render method.

Fragments let you group a list of children without adding extra nodes to the DOM.

const appContainer = document.getElementById('app')

function Form () {
  const handleSubmit = (e) => {
    e.preventDefault()
  }
  return (<form onSubmit={handleSubmit}>
    <input type="email" placeholder="email@example.com" />
    <input type="submit" value="Submit" />
  </form>)
}

function Content () {
  return <h2>Subscribe to our newsletter</h2>
}

ReactDOM.render(
  <>
    <Content />
    <Form />
  </>, appContainer)

Conclusion

The good part about it is that you can wrap those components in a variable and render them based on a condition if necessary.

const formComponent = <Form />
const contentComponent = isVisible ? <Content /> : null

const components = <>
  {contentComponent}
  {formComponent}
</>

ReactDOM.render(components, appContainer)

In a complex environment (ours is a WordPress plugin), it is a great way to control what gets delivered to the user.

See full example on CodePen:

Discussion

pic
Editor guide