Is there a way to avoid having two "root" elements in React?

Viewed 728

Normally you have to put a root element in your template, such as <div id="root"></div>. Then with React/jsx,you render a component (and its subcomponents) into root. That component (when rendered) might look like this <div id="main-wrapper">. The final render will have two roots, one called root and one called main-wrapper. Is there a cleaner way to render with React?

Instead of this:

<div id="root">
    <div id="main-wrapper>
        <section></section>
        <section></section>
        . . .
    </div>
</div>

Can I do this?

<div id="root">
    <section></section>
    <section></section>
    . . .
</div>
1 Answers

You could return a fragment from your top-level component rather than a top-level element:

const App = () => {
    return <>
        <section>stuff</section>
        <section>goes</section>
        <section>here</section>
    </>;
};

Before:

const App = () => {
    return <div id="main-wrapper">
        <section>stuff</section>
        <section>goes</section>
        <section>here</section>
    </div>;
};

ReactDOM.render(<App/>, document.getElementById("root"));
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

After:

// Stack overflow's Stack Snippets Babel is so massively out of date that I have to use
// <React.Fragment>...</React.Fragment> rather than <>...</>, but that's just for the
// on-site snippet.
const App = () => {
    return <React.Fragment>
        <section>stuff</section>
        <section>goes</section>
        <section>here</section>
    </React.Fragment>;
};

ReactDOM.render(<App/>, document.getElementById("root"));
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

Related