Skip to content

Proposal: combining classes using only className #154

Description

@rafikalid

Actual behaviour

We need to use third party libs like clsx to complish this very common behaviour

<div className={ clsx( 'class1', condition && 'class2', condiction2 ? 'class3' : null ) } />

Wanted behaviour

Use JSX to accomplish this common task directly

<div
     className = "class1"
     className = { condition && 'class2' }
     className = { condition2 ? 'class3' : null }
     />

// OR
<div
     className={ [
          'class1',
          condition && 'class2',
          condition3 ? 'class3' : null
     ] }
     />

This should compile everything to somthing like :

React.createElement( 'div', {className: ['class1', condition && 'class2', condition2 ? 'class3' : null ] } );

Activity

  1. rafikalid commented on Nov 10, 2022

    @rafikalid
    Author

    I propose in general to compile duplicated attributes to arrays as follow:

    <div
        className = "c1"
        className = "c2"
        className = "c3"
    />
    
    // TO
    
    React.createElement(Component, {
      className: [ 'c1', 'c2', 'c3' ]
    });

    and

    <div
        anyAttr = "value 1"
        anyAttr = { true }
        anyAttr = { callLogic() }
        anyAttr
        !anyAttr
    />
    
    // TO
    
    React.createElement(Component, {
      anyAttr: [ "value1", true, callLogic(), true, false ]
    });
  2. fabiospampinato commented on Jan 20, 2023

    @fabiospampinato

    This is a problem that must be solved at the framework level, React is just giving you a very basic API for setting classes, that's the problem.

  3. drwpow commented on Jun 7, 2025

    @drwpow

    I personally am a big fan of Svelte’s approach, allowing not only classname combining but with easy conditions built in:

    https://svelte.dev/playground/ca01d7704d2e411bbe9a9911de6ea8bb?version=5.33.16

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions