Home > Mobile >  Is there a better way to organize this dynamic class naming?
Is there a better way to organize this dynamic class naming?

Time:05-09

I have a variable extend which could be either an empty string '' or active, which is a CSS class.

Once the top div is clicked, all subsequent elements updates with "active"

<div
      className={`container ${extend ? "active" : ""}`}
      onClick={() => setExtend(!extend)}
    >
      <p className={`card ${extend ? "active" : ""}`}>Visa Card</p>
      <h1 className={`balance ${extend ? "active" : ""}`}>$55,343.15</h1>
</div>

then my CSS looks like this

.container {
&.active
}

.card {
&.active
}

.balance {
&.active
}


I feel like there is a lot of repetition in both CSS and JS and I am wondering if there is a more elegant way to do this

CodePudding user response:

For your JS:

// Use a function to help init classes with active state if needed
const addClasses = useCallback((baseClasses) => {
  const classes = [baseClass];

  if (extend) {
    classes.push('active');
  }
 return classes.join(' ');
}, [extend]);

return  <div
      className={addClasses('container')}
      onClick={() => setExtend(!extend)}
    >
      <p className={addClasses('container')}>Visa Card</p>
      <h1 className={addClasses('balance')}>$55,343.15</h1>

For your CSS, it depends on what you're doing in &.active. If each of them have the same active style then:

For your CSS:

.container, .card, .balance {
  &.active {
    // common style goes here
  }
}

CodePudding user response:

A good idea in your case may be use classnames package: https://www.npmjs.com/package/classnames. By this you can easily manage class names of your components.

  • Related