简体   繁体   中英

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

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

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
  }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM