skip to Main Content

I want to make this part of code in styles.css true, only if toggleSwitch2 is true

/* if toggleswitch2 false then  */
.react-flow .react-flow__handle {
}

/* if toggleswitch2true then */
.react-flow .react-flow__handle {
  width: 30px;
  height: 14px;
  border-radius: 3px;
  background-color: #784be8;
}

the problem is that the class that is being targeted by styles.css doesn’t exist as an element (for example div tag) inside jsx.

const [toggleSwitch2, setToggleSwitch2] = useState(false);

const handleToggleSwitch2 = () => {
  setToggleSwitch2(!toggleSwitch2);
};

<div className="toggle-switch-container2">
  <input id="toggle-switch2" type="checkbox" checked={ toggleSwitch2 } onChange={ handleToggleSwitch2 } />
  <label htmlFor="toggle-switch2">
    Make handles bigger
  </label>
</div>

2

Answers


  1. Don’t use conditional rendering in your CSS use it in your JSX code

    const styling = toggleSwitch2 && {
        width: "30px",
        height: "14px",
        borderRadius: "3px",
        backgroundColor: "#784be8"
    };
    
    <input style={styling} 
        //rest of input code
    />
    
    Login or Signup to reply.
  2. This might be helpful for you

    import React, { useState } from 'react';
    import './styles.css'; // Ensure that you've imported your external CSS file.
        
        function YourComponent() {
          const [toggleSwitch2, setToggleSwitch2] = useState(false);
        
          const handleToggleSwitch2 = () => {
            setToggleSwitch2(!toggleSwitch2);
          };
        
          return (
            <div className="toggle-switch-container2">
              <input
                id="toggle-switch2"
                type="checkbox"
                checked={toggleSwitch2}
                onChange={handleToggleSwitch2}
              />
              <label htmlFor="toggle-switch2">Make handles bigger</label>
              <div className={`react-flow__handle ${toggleSwitch2 ? 'active' : ''}`}>
                {/* Your content */}
              </div>
            </div>
          );
        }
        
        export default YourComponent;
    

    Style.css

    .react-flow__handle {
          /*default styles*/
        }
        
        .react-flow__handle.active {
          width: 30px;
          height: 14px;
          border-radius: 3px;
          background-color: #784be8;
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search