Having trouble getting help?
Contact Support
Contact Support
Prevent State Change in React Switch component
13 Dec 20242 minutes to read
The beforeChange event is triggered before the switch’s state is altered. This event provides an opportunity to intercept and potentially cancel the change action before it is applied. It allows for implementing conditional logic or validating the change prior to it being rendered on the UI.
import { enableRipple } from '@syncfusion/ej2-base';
import { SwitchComponent } from '@syncfusion/ej2-react-buttons';
import * as React from 'react';
import * as ReactDom from 'react-dom';
enableRipple(true);
// This function is called before the Switch state changes
function beforeChange(args) {
// Set cancel to true to prevent the switch state change
args.cancel = true;
}
function App() {
return (
<SwitchComponent
checked={true}
beforeChange={beforeChange}
/>
);
}
export default App;
ReactDom.render(<App />, document.getElementById('switch'));
import { enableRipple } from '@syncfusion/ej2-base';
import { SwitchComponent, BeforeChangeEventArgs } from '@syncfusion/ej2-react-buttons';
import * as React from 'react';
import * as ReactDom from 'react-dom';
// Enable ripple effect for Syncfusion components
enableRipple(true);
// This function is called before the Switch state changes
function beforeChange(args: BeforeChangeEventArgs) {
// Set cancel to true to prevent the switch state change
args.cancel = true;
}
// Render the Switch component with checked state
function App() {
return (
<SwitchComponent
checked={true}
beforeChange={beforeChange}
/>
);
}
export default App;
ReactDom.render(<App />, document.getElementById('switch'));