This blog will help you install and build your very first mobile app that is a STOPWATCH having just some small understanding of Javascript and ReactJS. You are going to have the most complete beginner understanding of building real-life native apps for both iOS and Android which means LEARN ONCE, WRITE ANYWHERE.

Stopwatch app using react native.

React Native

React Native lets you build mobile apps using only JavaScript. It uses the same design as React, letting you compose a rich mobile UI using declarative components. React Native lets you build your app faster with features like Hot Reloading (no need for recompilation).

React Native uses the same fundamental UI building blocks as regular iOS and Android apps, that means you are not building Web Apps but real-life Native Apps. Instead of using Swift, Kotlin or Java, you are putting those building blocks together with just using JavaScript and React.

Also, React Native combines smoothly with components written in Swift, Java, or Objective-C. It’s also easy to build part of your app in React Native, and part of your app using native code directly – that’s how the Facebook app works.

Installing React Native

0. You first need to download and install the latest Node version into your local machine. If already installed skip this step. You may follow https://nodejs.org/en/download/

1. Install expo-cli.


#installing expo-cli tool globally
npm install -g expo-cli
#or (if you are familiar with yarn or encountered some problem)
yarn global add expo-cli

2. Creating a new React Native project called “Stopwatch”.


#To your favorite location
#To install all dependencies for project
expo init Stopwatch
#Enter to blank and then enter the project name i.e. Stopwatch

#Move to project
cd Stopwatch

#Starting App
expo start
#or
npm start 
#or
yarn start

This would look like this…

React Native stopwatch
React Native stopwatch

3. Install the Expo client app on your iOS or Android phone and connect to the same wireless network as your computer. On Android, use the Expo app to scan the QR code from your terminal to open your project. On iOS, follow on-screen instructions to get a link.

For reference, the app would look like this, click on Scan QR Code and scan the QR Code from the local host which would open after expo start command

React Native stopwatch
React Native stopwatch

Note:- if you encountered any problem or it is not working in your physical device, then you can take the help of Emulators like XCode or Android Studios.
you just need to run commands like:- npm run ios, if you have XCode or npm run android for an android emulator.

4. Now that you have successfully run the app, let’s modify it. Open App.js in your text editor of choice and edit some lines. The application should reload automatically once you save your changes.

........
export default function App() {
  return (
    <View style={styles.container}>
      <Text>Welcome to Codersera</Text>
    </View>
  );
}
........
React Native stopwatch

Basics required before you proceed

-> You should have good knowledge about Javascript.
-> React Native is like React, but it uses native components instead of web components as building blocks. Hence, to understand the basic structure of a React Native app, you need to understand some of the basic React concepts, like JSX, components, state, and props.

Let’s start building a Stopwatch application

1. Let’s make the first separate React Component named Stopwatch.


#for making file stopwatch.container.js in directory stopwatch
touch ./stopwatch/stopwatch.container.js

2. Now open stopwatch.container.js, and start importing elements from modules.
Stylesheet element helps us in forming stylesheet and stylings to our dom elements.
Text is a built-in component that just displays some text.
View is like the <div> or <span>.
TouchableOpacity is for defining buttons, it has just some advances over Buttons.

#file: stopwatch.container.js

#import React and Component from react
import  React, { Component } from 'react';
#import these elements from react-native module
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';

3. Let’s now form it class-based component and export it as default.


#file: stopwatch.container.js

........
class StopwatchContainer extends Component {
    constructor(props){
        super(props);
    
    }
}

export default StopwatchContainer;

4. Let’s now specify a state for our component as we are going to build a stopwatch application which will dynamically change its content after every interval, and as we know for making dynamic screen we need to use state.


#file: stopwatch.container.js

........
constructor(props){
        super(props);

        this.state = {
            min: 0,
            sec: 0,
            msec: 0
        }
}
.........

5. Now let’s add render function in our class that will start giving shape to our stopwatch. It is the template section if you are familiar with react.js, and let’s use the imported components View and Text here.
and Use parameter style into our imported components and give it values which you will later find meaningful, style helps us in giving style to our respective component.
padToTwo is a simple javascript function that will be outside the class and it helps in making the digits in stopwatch exactly of length “2”.


#file: stopwatch.container.js
..........

let padToTwo = (number) => (number <= 9 ? `0${number}`: number);

..........
render(){
   return(
       <View style={styles.container}>
           <View style={styles.parent}>
               <Text style={styles.child}>{padToTwo(this.state.min) + ' : '}</Text>
               <Text style={styles.child}>{padToTwo(this.state.sec) + ' : '}</Text>
               <Text style={styles.child}>{padToTwo(this.state.msec)}</Text>
           </View>

#For Buttons
                <View style={styles.buttonParent}>
                    <TouchableOpacity style={styles.button}><Text style={styles.buttonText}>Reset</Text></TouchableOpacity>
                    <TouchableOpacity style={styles.button}><Text style={styles.buttonText}>Start</Text></TouchableOpacity>
                    <TouchableOpacity style={styles.button}><Text style={styles.buttonText}>Lap</Text></TouchableOpacity>
                </View>
       </View>
    );
}
..........

6. Now let’s form those styles which we gave to our respective component. So, we form a constant outside of class and use the Stylesheet component which we had imported from react-native above, observe the way we wrote styles of CSS here.


#file: stopwatch.container.js

..........
const styles = StyleSheet.create({
    parent: {
        display: "flex",
        flexDirection: "row",
        borderWidth:1,
        borderRadius: 80,
        borderColor: "#694966",
        backgroundColor: '#694966',
        paddingLeft: "8%",
        paddingRight: "8%",
        paddingTop: ".5%",
        paddingBottom: ".5%",
    },

    child: {
      fontSize: 40,
      color: "#C89933",
    },

    buttonParent: {
        display: "flex",
        flexDirection: "row",
        justifyContent: "space-around",
        marginTop: "12%",
    },

    button: {
        backgroundColor: "#694966",
        paddingTop: "5%",
        paddingBottom: "5%",
        paddingLeft: "5%",
        paddingRight: "5%",
        display: "flex",
        borderRadius: 20,
        borderWidth: 1,
        borderColor: "#694966",
        height: 60,
    },

    buttonText: {
        color: "#C89933",
        fontSize: 20,
        alignSelf: "center"
    }
});
...........

7. Now let’s import our StopwatchComonent into App.js file and further style our App.js the same way.


#file App.js

..........
import StopwatchContainer from "./stopwatch/stopwatch.container";

export default function App() {
  return (
    <View style={styles.container}>
      <Text style={styles.title}>Welcome to Codersera</Text>

      <StopwatchContainer />

    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    display: "flex",
    backgroundColor: '#DBD053',
    alignItems: 'center',
    justifyContent: 'flex-start',
    paddingTop: "8%",
  },

  title: {
    fontSize: 30,
    color: "#74526C",
    marginBottom: "8%"
  }

});

After Step 7 our stopwatch will look like this.

React Native stopwatch

8. Let’s have some modal/logic into our component now, which will be a simple JavaScript code.


#file: stopwatch.container.ts

..........
constructor(props){
        super(props);

        this.state = {
            min: 0,
            sec: 0,
            msec: 0
        }

        this.lapArr = [];

        this.interval = null;
    }

handleToggle = () => {
        this.setState(
            {
                start: !this.state.start
            },
            () => this.handleStart()
        );
    };

    handleLap = (min, sec, msec) => {
        this.lapArr = [
            ...this.lapArr,
            {min, sec, msec}
        ]

    };

    handleStart = () => {
        if (this.state.start) {
            this.interval = setInterval(() => {
                if (this.state.msec !== 99) {
                    this.setState({
                        msec: this.state.msec + 1
                    });
                } else if (this.state.sec !== 59) {
                    this.setState({
                        msec: 0,
                        sec: ++this.state.sec
                    });
                } else {
                    this.setState({
                        msec: 0,
                        sec: 0,
                        min: ++this.state.min
                    });
                }
            }, 1);

        } else {
            clearInterval(this.interval);
        }
    };

    handleReset = () => {
        this.setState({
            min: 0,
            sec: 0,
            msec: 0,

            start: false
        });

        clearInterval(this.interval);

        this.lapArr = [];
    };
............

9. Now call functions from Touchable Opacities, and some few DOM Manipulations into our template, Touchable Opacity has onPress prop which will help us in callbacks.


#file: stopwatch.container.js
.................
<View style={styles.buttonParent}>
                    <TouchableOpacity style={styles.button} onPress={this.handleReset}><Text style={styles.buttonText}>Reset</Text></TouchableOpacity>
                    <TouchableOpacity style={styles.button} onPress={this.handleToggle}><Text style={styles.buttonText}>{!this.state.start? 'Start': 'Stop'}</Text></TouchableOpacity>
                    <TouchableOpacity style={styles.button} onPress={()=>this.handleLap(this.state.min, this.state.sec, this.state.msec)} disabled={!this.state.start}><Text style={styles.buttonText}>Lap</Text></TouchableOpacity>
                </View>
..................

10. Now we need to form a list component where we have to show the list of our laps.


#forming empty file list.component.js
touch ./stopwatch/list.component.js

11. Let’s import some elements as usual from react-native and react.
ScrollView helps us to form a list that will be scrollable like you see in your mobile devices.
FlatList helps us in forming a list that can be dynamic. It can take many useful props.


#file: list.component.js
import React, {Component} from 'react';
import { ScrollView, FlatList, StyleSheet, Text } from 'react-native';

12. Now let’s make a class component named ListComponent and export it as usual.


#file: list.component.js 
..........
class ListComponent extends Component {
     
}

export default ListComponent;

13. Let’s now form the template for our List Container.
Here we again use the padToTwo function for making our number of at least two digits.
ScrollView, it helps us in making the list scrollable.
FlatList with its props data and renderItem, data takes the array as input and renderItem will loop through them and return some dom/list item.

 
#file: list.component.js
..........
let padToTwo = (number) => (number <= 9 ? `0${number}`: number);
..........
render() {
        return (
            <ScrollView style={styles.scroll}>
                <FlatList
                    data={this.props.lap}
                    renderItem={({item, index}) => <Text key={index+1} style={styles.item}>{`#${index}            `}{padToTwo(item.min)}:{padToTwo(item.sec)}:{padToTwo(item.msec)}</Text>}
                />
            </ScrollView>
        );
}

14. Let’s now style our component. You can use your imagination for styling.


#file: list.component.js
.........
const styles = StyleSheet.create({
    scroll: {
        maxHeight: "63%",
        backgroundColor: "#C89933",
    },

    item: {
        padding: 10,
        fontSize: 22,
        height: 44,
        color: "#5C415D",
        textAlign: "center",
        backgroundColor: "#fff",
        marginBottom: 1
    },
})
..........

If you reached here, then your stopwatch must look like this.

First React Native Application

15. Now let’s import our ListComponent into StopwatchContainer. and pass the props in it.


#file: stopwatch.container.js
..........
<ListComponent lap={this.lapArr} />
..........

This is how our Stopwatch looks like.

First React Native Application

Source: InApps.net

Rate this post
Read More:   Application Development Trends in 2022 for all industries
As a Senior Tech Enthusiast, I bring a decade of experience to the realm of tech writing, blending deep industry knowledge with a passion for storytelling. With expertise in software development to emerging tech trends like AI and IoT—my articles not only inform but also inspire. My journey in tech writing has been marked by a commitment to accuracy, clarity, and engaging storytelling, making me a trusted voice in the tech community.

Let’s create the next big thing together!

Coming together is a beginning. Keeping together is progress. Working together is success.

Let’s talk

Get a custom Proposal

Please fill in your information and your need to get a suitable solution.

    You need to enter your email to download

      Success. Downloading...