Custom toggle switch in React Native

Hi Guys, In this article, we are going to learn about Custom toggle switch in React Native. There are many dependencies and plugins available for the toggle switch, I had used one of them but I was facing many issues with that like it’s not customizable, in some libraries preselection is not working and code is very complex to customize so I decided to create own simple custom toggle switch in React Native. so let’s understand with an example.

Steps to create a custom toggle button

  • Create a Custom switch component all code for switch UI & on click will place in this component
  • Import this custom switch component in your file where you want to render this custom switch

1. Create a new project

I have already created a project, so I am creating a custom component and import it to the screen.

2. CustomSwitch.js

Here’s the source code for the Custom toggle switch component. create CustomSwitch.js and add the following code to it. I have created const CustomSwitch and pass props in it. and use react native hooks to save default values in the state.

3. Import CustomSwitch.js in Dashboard screen

On our main screen import the CistomSwitch.js component which we had created before and we have to pass some mandatory props which need to display custom switch

As you see in the above code, I have added six options that are mandatory. let’s understand usage.

  1. selectionMode : selectionMode use to set preselected option.
  2. roundCorner : Use this boolean to add or remove Rounded corners.
  3. option1 & option2 : Use this Text to set Toggle option like ON & OFF.
  4. onSelectSwitch : OnSelectSwitch const function triggers after toggle changes.
  5. selectionColor : SelectionColor use to set selection color.

4. Output:

Here’s the output on the Custom switch selection button in react native. just code and use source code, let me know if anyone has any queries.

Custom toggle switch in React Native

Thank you 🙂

Leave a Reply

Your email address will not be published.