Itbaran Baran
Itbaran Baran

Reputation: 29

antd Switch checked property

I want to ask a question about the Swtich component from antd the React UI library.

<Switch checked={true} />

When I set checked property I no longer can change it! I have looked at the API on the antd website but I can't understand why it doesn't work.

Please also have a look at my sample code here on codesandbox.io

Upvotes: 2

Views: 13309

Answers (3)

Mohammad Faisal
Mohammad Faisal

Reputation: 2363

here is how you can handle it

export default function App() {
  const [active, setActive] = useState(true);

  return (
    <div className="App" style={{ marginTop: 100 }}>
      <Switch onClick={() => setActive(!active)} checked={active} />
    </div>
  );
}

Upvotes: 1

id1
id1

Reputation: 221

import React, { useState } from "react";
import "./styles.css";
import "antd/dist/antd.css";
import { Switch } from "antd";

export default function App() {
  const [isStatus, setStatus] = useState(false);

  const buttonHandler = () => {
    setStatus((status) => !status);
  };

  return (
    <div className="App" style={{ marginTop: 100 }}>
      <Switch onChange={buttonHandler} checked={isStatus} />
    </div>
  );
}

Upvotes: 3

Yash Joshi
Yash Joshi

Reputation: 2784

It is because the component is controlled and the value is always set to true.

You can do 2 things here:

  1. Update checked to defaultChecked
  2. Add state variable and an onChange event. You can also check the working codesandbox: https://codesandbox.io/s/beautiful-archimedes-v26kq?file=/src/App.js:111-336
export default function App() {
  const [checked, setChecked] = React.useState(true);
  return (
    <div className="App" style={{ marginTop: 100 }}>
      <Switch checked={checked} onChange={setChecked} />
    </div>
  );
}

Read more about controlled component here: https://reactjs.org/docs/forms.html#controlled-components

Upvotes: 6

Related Questions