Home > Net >  how to add :before css conditionally react
how to add :before css conditionally react

Time:02-21

i want to conditionally add :before css selector to my dynamic product, currently its mutual fund but it can be later in future, please let me know how to do it

        <div  className={`${style.right_block}`}>
          <ul  className={`${style.three_points}`}>
            <li  className={`${style.mutual_fund}`} >{current_web.cat}</li>
            <li  className={`${style.beginner_icon}`}>{current_web.difficulty}</li>
            <li  className={`${style.time_icon}`}>{current_web.dur}</li>
          </ul>
        </div>

as you can see my product, difficulty, and dur(duration ) coming from api, i want to chnage product :before icon based on my product,

CodePudding user response:

If I understand the question correctly, you would like to conditionally add a :before css rule to a certain element?

<div  className={`${style.right_block}`}>
      <ul  className={`${style.three_points}`}>
        <li  className={(yourCondition ? style.nameOfStyleInCssFileWithBeforeRule : style.normalStyle)} >{current_web.cat}</li>
        <li  className={`${style.beginner_icon}`}>{current_web.difficulty}</li>
        <li  className={`${style.time_icon}`}>{current_web.dur}</li>
      </ul>
</div>

CodePudding user response:

I recommend to use useState:

const [ConditinClass , setConditinClass] = useState(styles.NoBeforeStateMent);

Then to style your component :

        <div className={ConditinClass} >
        ... your stuff
        </div>

And to switch to class with before :

setConditinClass(styles.classWithBefore)

Be sure to create both classes.

  • Related