Search code examples
cssreactjsreact-css-modules

Appending a class with Click messes up the whole css


I don't really know why transforming the X position while appending an additional class to make the slide effect isn't working as expected in React, as it does while using vanilla javascript. This is the code example

.inputModal {
  position: absolute;
  width: 500px;
  height: 150px;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  padding: 10px 20px;
  background-color: rgba(25, 26, 26, 0.74);
  left: -8px;
  top: 30%;
  box-shadow: 10px 15px 20px rgba(0, 0, 0, 0.5);
  transform: translateX(-93%);
  transition: all 0.3s ease-in-out;
} 

.InputModal.show {
transform: translateX(0px);
}

And the simple Component which should append the class show on button click

function InputModal() {
  const [toggleBtn, setToggleBtn] = useState(true);
  return (
    <div className={toggleBtn ? "inputModal" : "InputModal show"}>
      <Input />
      <div
        className="toggleBtn"
        onClick={() => {
          setToggleBtn(!toggleBtn);
        }}
      >
        <i className="fas fa-align-justify"></i>
      </div>
    </div>
  );
}

Once I click the toggle button(div) the show class is appended on to the div, but the div is losing all the previous set stylings and gets messed up


Solution

  • You should append instead of change the classes, just like:

    function InputModal() {
      const [toggleBtn, setToggleBtn] = useState(true);
      return (
        <div className={`inputModal ${toggleBtn ? "" : "InputModal show"}`}>
          <Input />
          <div
            className="toggleBtn"
            onClick={() => {
              setToggleBtn(!toggleBtn);
            }}
          >
            <i className="fas fa-align-justify"></i>
          </div>
        </div>
      );
    }