ABCman
ABCman

Reputation: 125

How to turn off toggle button by clicking other button in React JS?

Basically, we can turn off/on toggle button by clicking the toggle button. How can I turn off toggle by clicking other button (what is generated after turning on toggle) like this:
enter image description here

Sadly, I can only hidden the button by clicking it but not the toggle by using my current code...

Upvotes: 1

Views: 6622

Answers (2)

ABCman
ABCman

Reputation: 125

As the toggle switch is a component of my employer, I just use checkbox to replace in this example.

I think I can code for my question (as you can see my code shown as below) and I found why the toggle switch cannot be turned off by a button... It is because there is a bug in the toggle switch component of my employer and then I have eventually fixed the bug.

Anyway, let me show the code for this question (even it is not the answer for the fixing the bug that I really need):

import React from "react";
import "./styles.css";

export default function App() {
  const [isOn, setIsOn] = React.useState(
      { a: false , b: false, c: false }
    );

  const handleInputA = () => {
    setIsOn({ ...isOn, a: !isOn.a });
  }

  const handleInputB = (inputLabel) => {
    setIsOn({ ...isOn, b: !isOn.b });
  }

  const handleInputC = (inputLabel) => {
    setIsOn({ ...isOn, c: !isOn.c });
  }

  return (
    <>
      <input
        type="checkbox"
        checked={isOn.a}
        onClick={handleInputA}
      />a
      <br />
      <input
        type="checkbox"
        checked={isOn.b}
        onClick={handleInputB}
      />b
      <br />
      <input
        type="checkbox"
        checked={isOn.c}
        onClick={handleInputC}
      />c (The one that I want to do for this question.)
      <br />
      { isOn.c &&
        <button onClick={handleInputC}>Unselect C</button>
      }
    </>
  );
}

You may check to see the effect if you are interested: https://codesandbox.io/s/toggleswitch-tpkti

Upvotes: 0

MMH
MMH

Reputation: 786

You need to manage a state for the toggle switch through the external button click.

This is a reference code that should get you started.

import React from "react";

export default function App() {
  const [isOn, setIsOn] = React.useState(false);

  return (
    <>
      <input
        type="checkbox"
        checked={isOn}
        onClick={(e) => setIsOn(e.target.val)}
      />
      <br />
      <button onClick={() => setIsOn((prevState) => 
!prevState)}>Toggle</button>
    </>
  );
}

This code is available here: https://codesandbox.io/s/hungry-knuth-55eh0?file=/src/App.js

Upvotes: 1

Related Questions