css-ns icon indicating copy to clipboard operation
css-ns copied to clipboard

Do not add className prop to React.Fragment

Open olivierberthier opened this issue 5 years ago • 1 comments

Hello, great module, thanks for saving me a lot of time !

Issue

Nested React.Fragments receive className as a prop. Fragments at first level are ok but not when they are nested in other elements or in a map() function for exemple. It is not a big issue because it does not cause any error in production build but in development environment the console is filled of warnings.

Warning: Invalid prop `className` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.
    in Fragment (created by Example)
    in Connect(App)
    in Provider

Exemple & Way to reproduce

const { React } = require('./path/to/css-ns')('Exemple');

class Example extends React.Component {
  render () {
   const items = [
       'item-1',
       'item-2',
       'item-3'
    ];

    return (
      <div className='outer'>
           {items.map(item => (

              // This is the Fragment that receive the className prop
              <React.Fragment key={item}> 
                  {item !== 'item-1' && <div className='separator'></div>}
                  <div className='item'>{item}</div>
              </React.Fragment>

            ))}
      </div>
    )
  }
}

Suggestion

Check if the element in createElement is a Symbol or more precisely if _.toString() !== 'Symbol(react.fragment)'

return Object.create(opt.React, { // inherit everything from standard React
    createElement: { // ...except hijack createElement()
      value: function(_, props) {
        if (props && _.toString() !== 'Symbol(react.fragment)') props.className = ns(props.className);
        
        return opt.React.createElement.apply(opt.React, arguments);
      }
    }
  });

olivierberthier avatar Feb 26 '19 21:02 olivierberthier

Thanks a lot for filing a detailed issue!

Your proposal looks solid, I'll get back to this soon!

jareware avatar Mar 01 '19 14:03 jareware