Home > Net >  React - how to change css file with dyamic values
React - how to change css file with dyamic values

Time:08-11

I've a component with this input slider (works with radio buttons)

<input
 checked={settings[0]?.payments.length === 1 ? 'checked' : null}
 type='radio'
 id={payment.value}
 value={payment.value}
 onChange={
   settings[0]?.payments.length === 1
   ? setState(payment.value)
   : handleChange
></input>

And the checked radio button has this static bg color

[type=radio]:checked   label {
 background-color: #eab308;
 border-radius: 8px;
}

I work with tailwind so normaly i style inside my jsx file but for more complex stuff i use extra css file.

This is how i use it inside the jsx (Data comes from MongoDB)

const settingsstate = useSelector((state) => state.systemSettingsReducer);
const { settings } = settingsstate;

const bg = settings[0]?.color[0]?.bgColor;

<div className={`${bg}`}>

How can i use this dynamic colors inside my css file?

CodePudding user response:

You can use CSS variables:

<div style={{ "--bgColor": bg }}>Hello</div>

div {
  background-color: var(--bgColor);
}

CodePudding user response:

I recommend use the valeu that you are changing payment.value as parameter to change the Style Class. So you can do like:

<input
 checked={settings[0]?.payments.length === 1 ? 'checked' : null}
 type='radio'
 id={payment.value}
 className = {`payment.value == some_thing ? className_true : className_false`}
 value={payment.value}
 onChange={
   settings[0]?.payments.length === 1
   ? setState(payment.value)
   : handleChange
/>

  • Related