⚛️ Initiate a React app with multiple components on a single DOM element
Nikita Hlopov
Posted on March 9, 2020
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.
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:
Posted on March 9, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 6, 2024