Building your first React Native app: Stopwatch tutorial in React native

栏目: IT技术 · 发布时间: 4年前

内容简介:This blog will help you install and build your veryReact Native lets you build mobile apps using onlyReact 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
 
# All source is available here, you can either download 
# or follow the tutorial below to understand 
# each and every component individually 
 
https://github.com/codersera-repo/reactnative-stopwatch

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 .

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

. 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…

Building your first React Native app: Stopwatch tutorial in React native
Building your first React Native app: Stopwatch tutorial in React native

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

Building your first React Native app: Stopwatch tutorial in React native
Building your first React Native app: Stopwatch tutorial in React native

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>
  );
}
........
Building your first React Native app: Stopwatch tutorial in React native

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.

Stylesheetelement helps us in forming stylesheet and stylings to our dom elements.

Textis a built-in component that just displays some text.

View is like the <div> or  <span>.

TouchableOpacityis 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:  ,
            sec:  ,
            msec:  
        }
}
.........

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.

padToTwois 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 ? ` ${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.

Building your first React Native app: Stopwatch tutorial in React native

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:  ,
            sec:  ,
            msec:  
        }
 
        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:  ,
                        sec: ++this.state.sec
                    });
                } else {
                    this.setState({
                        msec:  ,
                        sec:  ,
                        min: ++this.state.min
                    });
                }
            }, 1);
 
        } else {
            clearInterval(this.interval);
        }
    };
 
    handleReset = () => {
        this.setState({
            min:  ,
            sec:  ,
            msec:  ,
 
            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.

ScrollViewhelps us to form a list that will be scrollable like you see in your mobile devices.

FlatListhelps 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.

FlatListwith 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 ? ` ${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.

Building your first React Native app: Stopwatch tutorial in React native

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.

Building your first React Native app: Stopwatch tutorial in React native

Yippeeee, we have completed our working stopwatch which will work on both iOS and Android , and it is our Native App, not some laggy Web App.

Read more:

How useful was this post?

Click on a star to rate it!

Post Views: 3,505


以上所述就是小编给大家介绍的《Building your first React Native app: Stopwatch tutorial in React native》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

计算几何

计算几何

周培德 / 2008-7 / 69.00元

《计算几何:算法设计与分析(第3版)》系统地介绍了计算几何中的基本概念、求解诸多问题的算法及复杂性分析,概括了求解几何问题所特有的许多思想方法、几何结构与数据结构。全书共分11章,包括:预备知识,几何查找(检索),多边形,凸壳及其应用,Voronoi图、三角剖分及其应用,交与并及其应用,多边形的获取及相关问题,几何体的划分与等分、算法的运动规划、几何拓扑网络设计、随机几何算法与并行几何算法等。一起来看看 《计算几何》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器