Workaround to add className to Fragment in React

Fragments let you group a list of children without adding extra nodes to the DOM. - https://reactjs.org/docs/fragments.html

What Fragments tries to solve it's the unnecessary dom elements but this doesn't mean that Fragments will replace div entirely. If you need to add a className there, it's clear that either you add a dom element in this case another div or add the className to its parent.


Using Fragment means not adding an extra node to DOM.

If you want to assign a className to a node then you'll have to use div.


  1. Create a css file and import it inside your App.js
  2. Create a higher order component withClass.js like below

    import React from  'react';
    
    const withClass = (WrappedComponent, className) => {
        return props => (
            <div className={className}>
                <WrappedComponent {...props} />
            </div>
        );
    };
    
    export default withClass;
  1. Import your hoc too.
  2. In your App.js write something like below

    <React.Fragment>
        <p>Some JSX code here</p>
    <React.Fragment>
    
    export default withClass(App, classes.App);

I created .App class inside my css file and imported it so that i can use it later with classes.App. This way you can apply any css class that you create inside your css.You can use the same wrapperComponent to wrap every component you have, by simply importing it and changing export in your component. You just have to make classname of your choice and use it in export statement of your component. When you write props with spread operator(...). All the props from your component will be passed to this wrapperComponent.

PS : English is not my native language so I am not good at explaining but this code will do the trick. Would appreciate a moderator taking look into my explanation.