Skip to content
Related Articles

Related Articles

ReactJS UI Ant Design Switch Component

View Discussion
Improve Article
Save Article
  • Last Updated : 21 May, 2021
View Discussion
Improve Article
Save 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.


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) => {
      }} /> <br />
      <p>Current Mode of Switch: {`${currentValue}`} </p>

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:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!