React Native Dynamically Change Horizontal ProgressBar Progress on Button Click Tutorial

Guys, Today I am going to elaborate that how we can change the React Native ProgressBar progress dynamically on button click with complete source code. Basically, React Native provides ProgressBarAndroid  component for Android and ProgressViewIOS  component for iOS. So, we are going to render correct component for correct platform through single piece of code. This is possible through the react native Platform  API. Through Platform API, we can detect the platform on which app is running and if the app is running on Android device then we will render ProgressBarAndroid  component or if app is running on iOS deice then we will render ProgressViewIOS  component.

In brief, what I am doing in Dynamically Change Horizontal ProgressBar Progress on Button Click tutorial?

  • First of all, through react native Platform API, I am going to detect the platform and render its corresponding component.
  • Then on button click, I am going to generate a random number through javascript random  function and set this generated number as the ProgressBar’s progress. The ProgressBar component takes number from 0 to 1 as its progress value and javascript random function generates random number from 0 ( included ) to 1 ( excluded ).

Let’s get started…

Step – 1: Import required components from react , react-native  packages.

Step – 2: Implement constructor  method.

Step – 3: Implement changeProgress  custom method which is responsible to generate a random number and update the  progressBarProgress  state variable with this newly generated random number.

Explanation:

  • As you can see in the above code snippet, I am using javascript toFixed(<number>)  method. This method is responsible to convert a number into string and restrict the number of digits after decimal. In our case, I want only 1 digit after decimal. That’s why I am using toFixed(1) , because toFixed  function converts a number into string I am using a parseFloat  javascript function to convert a string into number.

Step – 4: Implement componentDidMount  method.

Step – 5: Implement render  method.

Explanation:

  • As you can see in the above code snippet, I am detecting the platform using the Platform API and render correct component on the correct platform.

Step – 6: Implement styles for all required components.

Complete Source Code:

Step – 7: Apply react-native run-android  command on terminal to run app in Android devices or use react-native run-ios  to run app in iOS devices.

  • iOS Screenshot:

  • Android Screenshot:

Enjoy Guys…

Leave a Reply

Your email address will not be published. Required fields are marked *