Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Workaround to add className to Fragment in React

Tags:

I am trying to create a stateless component in React with the sole purpose of acting as a reusable wrapper. I am also using CSS Modules because I want to have fully modular CSS.

The thing is I don't want to add unnecessary elements (and even more so <div>s), but instead I want to use React's Fragments.

Now, the problem I have is Fragment (at least for now) do not accept classNames. So if I try this:

// In Wrapper.js:

import React, { Fragment } from 'react' import styles from './Wrapper.css'  const wrapper = (props) => (     <Fragment className={styles.wrapper}>         {props.children}     </Fragment> )  export default wrapper 

In (for example) Navbar.js:

import React from 'react' import styles from './Navbar.css' import Wrapper from '../../Layout/Wrapper'  const navBar = (props) => (     <nav className={styles.navBar}>         <Wrapper>             This is the site's main navigation bar.         </Wrapper>     </nav> )  export default navBar 

Now I can of course, use a div instead of the Fragment, but is there any other workaround to avoid using unnecessary markup, of which I am totally unaware at this hour of the night? :)

Thanks in advance for any insight, recommendation, correction, or any other form of help!

like image 699
NTP Avatar asked Mar 02 '18 13:03

NTP


People also ask

Can you put a className on a React fragment?

If you want a className, this className will have to apply to an element, no ? And Fragments do not render any element, so you can't use a className with it.

How do I add a className to a React component?

To pass class names as props to a React component:Pass a string containing the class names as a prop. Destructure the prop in the child component. Assign the class names to an element, e.g. <h2 className={className}>Content</h2> .

Can we use class instead of className in React?

Explanation: The only reason behind the fact that it uses className over class is that the class is a reserved keyword in JavaScript and since we use JSX in React which itself is the extension of JavaScript, so we have to use className instead of class attribute.

Which is better <> or React fragment?

<> is the shorthand tag for React. Fragment which allows us to group a list of elements without wrapping them in a new node. The only difference between them is that the shorthand version does not support the key attribute.


1 Answers

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 its the unnecessary dom elements but this doesn't mean that Fragments will replace div entirely. If you need to add a className there, its clearl that either you add a dom element in this case another div or add the class to its parent.

like image 195
John Baker Avatar answered Sep 21 '22 06:09

John Baker