Build A simple To-Do App With React Native
Setting
up the Environment:
Installing
the Dependencies:
To setting up a react native Development environment
you need to Install Nodejs, Java SDK ,
Android Studio.
Installing
Nodejs and JAVA –SDK:
You can install Node js and java-SDK using Chocolaty Package manager.
First you need to install Chocolaty package manager
from https://chocolatey.org/.
Then install Nodejs and Java SdK running the below command from Command prompt
as a administrator.
choco install -y nodejs-lts openjdk11
Installing
android Studio:
You can download and install Android studio from https://developer.android.com/studio
.
While Installing The Android studio make sure the
following Boxes are checked.
Andriod Sdk, Android
Sdk Platform, Android Virtual device.
Android
Studio Automatically installs The latest version By Default , But the Android
12 Is required Can be installed using sdk Manager.
Select Sdk Mager àShow PackagesàSelect
Android 12 àMake
sure The Following Item Also Checked.
1.Android SDK Platform
latest version.
2. Intel x86 Atom_64
System Image or Google APIs Intel x86 Atom System Image.
finally Click Apply to download and install.
Configure
the ANDROID_HOME Environment variable:
Click on Edit Environment variable àCreate a new
Environment Variable named ANDROID_HOME and value as Android Sdk location From
Sdk Manager.
You Can Verify The ANDROID_HOME Added by Running The
Following Command In PowerShell.
Get-ChildItem -Path Env:\
Add
platform Tools to path:
Click On Edit Environment Variable àselect
Path variable àClick
edit àClick
New and add the path.
The default path is
= %LOCALAPPDATA%\Android\Sdk\platform-tools.
Preparing
The Android device:
You need a Android device to run the application it
can be either a physical device or a virtual device,
Using physical Device:
To use a physical device you should follow the
Instructions given in the Link:
https://reactnative.dev/docs/running-on-device.
Using A virtual device:
To use A Virtual device follow the instructions In
the link:
https://developer.android.com/studio/run/managing-avds.html
Create
and Run Project:
Creating
A React Native Application Using React Native-cli:
You Can Create your project using react Native By running The following Command,
npx react-native init
projectname
On the execution of the above command will create a
folder on the project name with all the files need to run an application , you
can navigate to the project folder using any IDE and run the application .
Running
your React Native application:
Start
Metro
First, you will need to start Metro, the JavaScript
bundler that ships with React Native. Metro "takes in an entry file and
various options, and returns a single JavaScript file that includes all your
code and its dependencies.
You Can Start Metro By Running the Following
command,
npx react-native start.
Note: Before
starting the metro you should start your virtual device using android studio
Start
your application:
Let Metro Bundler run in its own terminal. Open a
new terminal inside your React Native project folder. Run the following,
npx react-native
run-android
If everything is set up correctly, you should see
your new app running in your Android emulator shortly.
Creating
the To-do App:
Creating
the Template:
Template define the structure of the components
inside the main component. In this Todo app we are using three components
(header, Form ,Todo List)
Example:
import React from 'react';
import React from 'react';
import { View,Text, StatusBar,StyleSheet} from 'react-native'
const App=()=>{
return(
<View style={{backgroundColor:'skyblue',flex:1}}>
<StatusBar hidden={false} backgroundColor='blue' />
<View>
{/**Header */}
</View>
<View>
{/**form */}
</View>
<View>
{/**todolist */}
</View>
</View>
)
}
Creating the components and render them inside the
main app component:
Header:
first create a component folder and create header.js
file, then create the header component
and render the component inside app component.
Example:
import React from 'react';
import { View,Text,StyleSheet} from 'react-native'
const Header1 =()=>{
return(
<View style={styles.header}>
<Text style={styles.head}>Todo App</Text>
</View>
)
}
export default Header1
const styles = StyleSheet.create({
header:{height:60,backgroundColor:'darkblue',justifyContent:'center',alignItems:'flex-start'},
head:{color:'white',fontSize:20,fontWeight:"bold",textAlignVertical:'center',marginLeft:10}
})
Creating
a dummy List And display:
Now let us create a Dummy list Items and display
them in our app, first using useState create a array of tasks. Before return
statement. Then render the array items as a flatlist. for that
first create a component to render the tasks.
1.creating the component:
import React from 'react';
import {View,Text} from 'react-native';
const Tasks=({item})=>{
return(
<View style={{height:50,flexDirection:'row',backgroundColor:'white',margin:10,alignItems:'center'}}>
<View style={{flex:0.8}}>
<Text style={{color:'black',fontSize:20,fontWeight:'bold',marginHorizontal:25,textAlignVertical:'center'}}>{item.task}</Text>
</View>
</View>
)
}
export default Tasks
this component will render the Items separately now
render the items inside the flatlist by passing the function item as props
value.
import React, { useState } from 'react';
import {Button, FlatList, StyleSheet,Text,TouchableOpacity,View,StatusBar} from 'react-native';
import Header1 from '../components/Header';
import Tasks from '../components/todolist';
import AddTodo from '../components/addtodo';
const App=()=>{
const[todo, setTodo]=useState([
{task:'wakeup', id:1},
{task:'workout',id:2}
])
return(
<View style={styles.container}>
<StatusBar hidden={false} backgroundColor='darkblue'/>
<Header1 />
<Text style={styles.header}>Todo Items</Text>
<View style={styles.list}>
<FlatList
data={todo}
renderItem={({item})=>( <Tasks item={item} />)}
keyExtractor={(item) => item.id}
/>
</View>
</View>
)
}
export default App
const styles =StyleSheet.create({
container:{flex:1,
backgroundColor:'skyblue',
},
list:{flex:0.7, flexDirection:'row',height:100},
header:{padding:10,backgroundColor:'blue',color:'white',fontSize:20,fontWeight:'bold'}
})
Output:
Adding Delete
Option:
This
will give you the delete feature for that we we use Touchable opacity inside
the list component. On press it will delete the respective Task.
import React from 'react';
import {View,Text,TouchableOpacity} from 'react-native';
const Tasks=({item,pressHandler})=>{
return(
<View style={{height:50,flexDirection:'row',backgroundColor:'white',margin:10,alignItems:'center'}}>
<View style={{flex:0.8}}>
<Text style={{color:'black',fontSize:20,fontWeight:'bold',marginHorizontal:25,textAlignVertical:'center'}}>{item.task}
</Text>
</View>
<View style={{flex:0.2}}>
<TouchableOpacity onPress={()=>pressHandler(item.id)}>
<Text style={{color:'red',fontSize:20,fontWeight:'bold',marginRight:10,backgroundColor:'skyblue'}}>Delete</Text>
</TouchableOpacity>
</View>
</View>
)
}
export default Tasks
we
need to create press handler function inside the main component because the
list array is created inside the main component. While pressing the delete it
will update the array without the respective task.
import React, { useState } from 'react';
import {Button, FlatList, StyleSheet,Text,TouchableOpacity,View,StatusBar} from 'react-native';
import Header1 from '../components/Header';
import Tasks from '../components/todolist';
import AddTodo from '../components/addtodo';
const App=()=>{
const[todo, setTodo]=useState([
{task:'wakeup', id:1},
{task:'workout',id:2}
])
const pressHandler=(id)=>{
setTodo((prevTodo)=>{return prevTodo.filter(todo=> todo.id != id)})
}
return(
<View style={styles.container}>
<StatusBar hidden={false} backgroundColor='darkblue'/>
<Header1 />
<Text style={styles.header}>Todo Items</Text>
<View style={styles.list}>
<FlatList
data={todo}
renderItem={({item})=>( <Tasks item={item} pressHandler={pressHandler} />)}
keyExtractor={(item) => item.id}
/>
</View>
</View>
)
}
export default App
const styles =StyleSheet.create({
container:{flex:1,
backgroundColor:'skyblue',
},
list:{flex:0.7, flexDirection:'row',height:100},
header:{padding:10,backgroundColor:'blue',color:'white',fontSize:20,fontWeight:'bold'}
})
Output:
Adding Item to the
List:
Creating A form:
To add a task Item To the List First we need to create the form
component and render it inside the main component.
import React, { useState } from 'react';
import {Button,Text,TextInput,View} from 'react-native';
const AddTodo=()=>{
const [item,setItem]= useState('')
const changevalue=(text)=>{
setItem(text)
}
return (
<View style={{flex:0.2}}>
<TextInput
placeholder='create a new Todo'
value={item}
onChangeText={changevalue}
style={{borderWidth:1,margin:10,backgroundColor:'white',borderRadius:20}}
/>
<Button title='Add Todo' color={'blue'}/>
</View>
)
}
export default AddTodo
By
rendering this component inside the main App component after the Header
component You will get A output like,
We need to add a function to add the task in the array while pressing
the add todo button.
import React, { useState } from 'react';
import {Button,Text,TextInput,View} from 'react-native';
const AddTodo=({submitHandler})=>{
const [item,setItem]= useState('')
const changevalue=(text)=>{
setItem(text)
}
return (
<View style={{flex:0.2}}>
<TextInput
placeholder='create a new Todo'
value={item}
onChangeText={changevalue}
style={{borderWidth:1,margin:10,backgroundColor:'white',borderRadius:20}}
/>
<Button title='Add Todo' color={'blue'} onPress={()=>{submitHandler(item)}} />
</View>
)
}
export default AddTodo
the submit handler should be inside the main component , because the
array is inside the main component.by clicking the add todo button the submit
handler function will update the array with new tasks.
Adding Todo Items:
import React, { useState } from 'react';
import {Button, FlatList, StyleSheet,Text,TouchableOpacity,View,StatusBar} from 'react-native';
import Header1 from '../components/Header';
import Tasks from '../components/todolist';
import AddTodo from '../components/addtodo';
const App=()=>{
const[todo, setTodo]=useState([
{task:'wakeup', id:1},
{task:'workout',id:2}
])
const pressHandler=(id)=>{
setTodo((prevTodo)=>{return prevTodo.filter(todo=> todo.id != id)})
}
const submitHandler=(item)=>{
setTodo((prevTodo)=>{return[
{task:item, id:Math.random().toString()},
...prevTodo
]})
}
return(
<View style={styles.container}>
<StatusBar hidden={false} backgroundColor='darkblue'/>
<Header1 />
<AddTodo submitHandler={submitHandler}/>
<Text style={styles.header}>Todo Items</Text>
<View style={styles.list}>
<FlatList
data={todo}
renderItem={({item})=>( <Tasks item={item} pressHandler={pressHandler} />)}
keyExtractor={(item) => item.id}
/>
</View>
</View>
)
}
export default App
const styles =StyleSheet.create({
container:{flex:1,
backgroundColor:'skyblue',
},
list:{flex:0.7, flexDirection:'row',height:100},
header:{padding:10,backgroundColor:'blue',color:'white',fontSize:20,fontWeight:'bold',marginTop:40}
})
Output:
Adding Switch for
Todo status:
import React, {useState} from 'react';
import {View,Text,TouchableOpacity,Switch} from 'react-native';
const Tasks =({item,pressHandler})=>{
const [checked, setChecked]= useState(false);
const toggleswitch=()=>{setChecked (!checked)};
return(
<View style={{height:50,flexDirection:'row',backgroundColor:'white',margin:10,alignItems:'center'}}>
<View style={{flex:0.7}}>
<Text style={{color:'black',fontSize:20,fontWeight:'bold',marginHorizontal:25,textAlignVertical:'center'}}>{item.task}</Text>
</View>
<View style={{flex:0.2}}>
<Switch
trackColor={{ false: 'red', true: "green" }}
thumbColor={checked ? "grey" : "grey"}
value={checked}
onValueChange={toggleswitch}
style={{marginRight:20}}
/>
</View>
<View style={{flex:0.1}}>
<TouchableOpacity onPress={()=>pressHandler(item.id)}>
<Text style={{color:'black',fontSize:20,fontWeight:'bold',padding:5,marginRight:15,backgroundColor:'orangered',borderRadius:25}}>X</Text>
</TouchableOpacity>
</View>
</View>
)
}
export default Tasks
Output:
Adding Validation to
form:
We set a specific length to the Task Name so it will not allow empty values.
const submitHandler=(item)=>{
if (item.length >5) {setTodo((prevTodo)=>{return[
{task:item, id:Math.random().toString()},
...prevTodo
]})}
else{
Alert.alert('warning','length must be
> 5',[{text:'OK'}])
}
While pressing Add Todo Button it will Validate the Task Name length if
its lesser than the standard setting Length it will give a alert.
Finally the To-do Application will look like,
Comments
Post a Comment