Home > Software engineering >  Changeing style in module.css on call function in React
Changeing style in module.css on call function in React

Time:04-03

I was thinking how can I change a slider color when call the function. I'm new in React and cannot find solution about module.css.

please be understanding.

import React, { useState } from 'react';

import styles from './SwitchButton.module.css';

function SwitchButton() {const \[sliderButton, setSliderButton\] = useState(false);

function toggleButton() {
    if (sliderButton === false) {

        console.log('right');
        setSliderButton(true);

    } else if (sliderButton === true) {

        console.log('left');
        setSliderButton(false);
    }
}

return (
    \<div class={styles.container} onClick={toggleButton}\>
        \<button class={\`${styles.slider} ${styles.sliderLeft}\`}\>Leftside\</button\>
        \<button class={\`${styles.slider} ${styles.sliderRight}\`}\>Rightside\</button\>
    \</div \>
);

}

export default SwitchButton;

I tried find solution on google

CodePudding user response:

Sure, you can toggle a conditional class defined in your CSS module from within your React component:

const [sliderButton, setSliderButton] = useState(false)
const [specialClass, setSpecialClass] = useState("")
const toggleButton = () => {
  console.log(sliderButton ? "left" : "right")
  setSliderButton(!sliderButton)]
  // change the class:
  setSpecialClass(sliderButton ? styles.on : styles.off)
}
return (
  <div className={styles.container} onClick={toggleButton}>
    <button className={`${styles.slider} ${styles.sliderLeft}`}>
      Leftside
    </button>
    <button className={`${styles.slider} ${styles.sliderRight}`}>
      Rightside
    </button>
    <div className={specialClass}>My class will change when the button is toggled.</div>
  </div>
)

CodePudding user response:

how can I change a slider color when call the function

you can do this as below

1.maintain state for toggle on or off,currently you are doing this with sliderButton(good)

2.use this sliderButton to check what class to use or which button to render if off user class for right or render right button ,else if on use class left of render left button

let first modify you toggle function as like this

  function toggleButton() {
        setSliderButton(!sliderButton);
   }

now you can use its value to render buttons,i assume one button will be shown and only class has to be changed

return (

<div class={styles.container} onClick={toggleButton}>
    <button className={(toggleSlider) ? styles.slider   " "   styles.sliderLeft : styles.slider   " "   styles.sliderRight}>{toggleSlider?"LeftButton":"RightButton"}</button>
</div >
);
  • Related