react-bootstrap component Switches not working
Solution 1
Simple FormCheck is working for me:
<FormCheck
id="switchEnabled"
type="switch"
checked={this.state.settings.enabled}
onChange={this.toggleEnabled}
label="Enable"
/>
The key point was to provide id. Another important thing (to load the initial value) was to use checked property.
Solution 2
Unfortunately documentation for the switch isn't the greatest. Nevertheless, the following should help with setting up the switch for your use.
const [isSwitchOn, setIsSwitchOn] = useState(false);
const onSwitchAction = () => {
setIsSwitchOn(!isSwitchOn);
};
...
<Form>
<Form.Switch
onChange={onSwitchAction}
id="custom-switch"
label="anything you want to put here"
checked={isSwitchOn}
disabled // apply if you want the switch disabled
/>
</Form>
...
Solution 3
I found an approach.
import React from "react";
import ReactDOM from "react-dom";
import { Container, Form, FormCheck, Button } from "react-bootstrap";
import "./styles.css";
import "bootstrap/dist/css/bootstrap.min.css";
function App() {
const [swt, setSwt] = React.useState(true);
const [swt2, setSwt2] = React.useState(true);
return (
<Container className="App">
Aprroch 1
<FormCheck custom type="switch">
<FormCheck.Input isInvalid checked={swt} />
<FormCheck.Label onClick={() => setSwt(!swt)}>
{`Value is ${swt}`}
</FormCheck.Label>
</FormCheck>
Approch 2
<Form.Check custom type="switch">
<Form.Check.Input isInvalid checked={swt2} />
<Form.Check.Label onClick={() => setSwt2(!swt2)}>
{`Value is ${swt2}`}
</Form.Check.Label>
</Form.Check>
</Container>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Solution 4
If you add the custom
property it will show the switch button, but I'm still not able to toggle the switch...
<Form>
<Form.Check
custom
type="switch"
id="custom-switch"
label="Check this switch"
/>
</Form>
Solution 5
I had a similar issue and adding custom as suggested in another answer showed the switch correctly but similarly the toggle would now work.
I noticed that I was pointing at an older version of react-bootstrap so changed this to point to the current version which at the time is v1.0.0-beta.16 and this allowed the toggle to work and custom to be removed.
So best to make sure you are pointing at the latest version of react-bootstrap if you're having problems like this: React Bootstrap
Mo.
Every nice creation start from imagination followed by dedication. Contacts 👇 Portfolio LinkedIn
Updated on June 24, 2022