Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

ReactJS UI Ant Design Switch Component

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Ant Design Library has this component pre-built, and it is very easy to integrate as well. Switch components are used to toggle the state of a single setting on or off. We can use the following approach in ReactJS to use the Ant Design Switch Component.

Switch Methods:

  • blur(): This method is used to remove the focus from the element.
  • focus(): This method is used to get the focus on the element.

Switch Props:

  • autoFocus: It is used to get focus when the component is mounted.
  • checked: It indicates whether the switch is checked or not.
  • checkedChildren: It is the content that is to be shown when the state is checked.
  • className: It is used to pass the class name for this switch.
  • defaultChecked: It indicates whether to set the initial state or not.
  • disabled: It is used to disable the switch.
  • loading: It is used to show to loading state of the switch.
  • size: It is used to denote the size of the switch.
  • unCheckedChildren: It is the content that is to be shown when the state is unchecked.
  • onChange: It is the callback function which is triggered when state changes.
  • onClick: It is the callback function which is triggered on click event.

Creating React Application And Installing Module:

  • Step 1: Create a React application using the following command:

    npx create-react-app foldername
  • Step 2: After creating your project folder i.e. foldername, move to it using the following command:

    cd foldername
  • Step 3: After creating the ReactJS application, Install the required module using the following command:

    npm install antd

Project Structure: It will look like the following.

Project Structure

Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.

App.js




import React, { useState } from 'react'
import "antd/dist/antd.css";
import { Switch } from 'antd';
  
export default function App() {
  
  const [currentValue, setCurrentValue] = useState(false)
  
  return (
    <div style={{ display: 'block', width: 700, padding: 30 }}>
      <h4>ReactJS Ant-Design Switch Component</h4>
      <Switch onChange={(value) => {
        setCurrentValue(value)
      }} /> <br />
      <p>Current Mode of Switch: {`${currentValue}`} </p>
  
    </div>
  );
}

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Reference: https://ant.design/components/switch/

My Personal Notes arrow_drop_up
Last Updated : 21 May, 2021
Like Article
Save Article
Similar Reads
Related Tutorials