Search code examples
reactjsreact-hooksreactstrap

How can I change customswitch label on/off in reactstrap?


I use reactstrap customswitch in my project. How can I change label on/off?

const ProfileSwitch = ({title, text, name, id, label}) => {
    return <div className="profile-switch">
        <div className="profile-switch__text">
            <p>{title}</p>
            <span>{text}</span>
        </div>
        <CustomInput type="switch" id={id} name={name} label={label} />
    </div>
}

export default ProfileSwitch;

Solution

  • You can handle this situation with toggle and useState.

    import React, { useState } from "react";
    import { CustomInput } from "reactstrap";
    
    const ProfileSwitch = ({ title, text, name, id, label }) => {
      const [isToggled, setToggled] = useState(false);
      const toggleTrueFalse = () => setToggled(!isToggled);
    
      return (
        <div className="profile-switch">
          <div className="profile-switch__text">
            <p>{title}</p>
            <span>{text}</span>
          </div>
          <CustomInput
            onClick={toggleTrueFalse}
            type="switch"
            id={id}
            name={name}
            label={isToggled === true ? "on" : "off"}
          />
        </div>
      );
    };
    
    export default ProfileSwitch;
    
    ProfileSwitch.defaultProps = {
      title: "title",
      text: "text"
    };
    

    I've forked your code, so here's the solution on codesandbox