Reputation: 29
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
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
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
Reputation: 2784
It is because the component is controlled and the value is always set to true
.
You can do 2 things here:
checked
to defaultChecked
onChange
event. You can also check the working codesandbox: https://codesandbox.io/s/beautiful-archimedes-v26kq?file=/src/App.js:111-336export 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