EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

React Native SQLite

By Rahul DubeyRahul Dubey

Home » Software Development » Software Development Tutorials » React Native Tutorial » React Native SQLite

React Native SQLite

 Introduction to React Native SQLite

SQLite can be defined as an SQL database that is open source and stores data to a text file on a device. One can perform all Create, Read, Update, and Delete SQL transactions in the SQLite database. For mobile development, the SQLite database holds major importance. SQLite database contains a schema of tables with their fields. All of the data saved to SQLite database tables is saved as application data and it takes space in internal memory. With an increase in records saved or data to the SQLite database, the application data also increases. SQLite database is very easy to connect in React-Native because of pre-available libraries in it.

How to Create an SQLite Database in React-Native?

For the SQLite database, we have used SQLite3 Native-Plugin which works for both iOS and Android.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

1. Components of pages-folder

  • Custombutton.js

import React from 'react';
import { TouchableOpacity
, Text
, StyleSheet } from 'react-native';
const Mybutton = props => {
return (
<TouchableOpacity style={styles.button} onPress={props.customClick}>
<Text style={styles.text}>{props.title}</Text>
</TouchableOpacity>
);
};
const styles = StyleSheet.create({ button: {
alignItems: 'center',
backgroundColor: '#df36eb',
color: '#ffffff',
padding: 11,
marginTop: 15,
marginLeft: 36,
marginRight: 36,
},
text: {
color: '#ffffff',
},
});
export default Mybutton;

  • Customtext.js

import React from 'react';
import { TouchableHighlight
, Text
, StyleSheet } from 'react-native';
const Mytext = props => {
return <Text style={styles.text}>{props.text}</Text>;
};
const styles = StyleSheet.create({ text: {
color: '#111825',
fontSize: 19,
marginTop: 15,
marginLeft: 36,
marginRight: 36,
},
});
export default Mytext;

  • Customtextinput.js

import React from 'react';
import { View
, TextInput } from 'react-native';
const Mytextinput = props => {
return (
<View
style={{ marginLeft: 36,
marginRight: 36,
marginTop: 49,
borderColor: '#61fab8',
borderWidth: 1,
}}>
<TextInput
underlineColorAndroid="transparent"
placeholder={props.placeholder}
placeholderTextColor="#61fab8"
keyboardType={props.keyboardType}
onChangeText={props.onChangeText}
returnKeyType={props.returnKeyType}
numberOfLines={props.numberOfLines}
multiline={props.multiline}
onSubmitEditing={props.onSubmitEditing}
style={props.style}
blurOnSubmit={false}
value={props.value}
/>
</View>
);
};
export default Mytextinput;

2. Components of displays-folder

  • DeleteUser.js

import React from 'react';
import { Button
, Text
, View
, Alert } from 'react-native';
import Mytextinput from './pages/Customtextinput'; import Mybutton from './pages/Custombutton';
import { openDatabase } from 'react-native-sqlite-storage'; var db = openDatabase({ name: 'UserDatabase.db' });
export default class UpdateUser extends React.Component { constructor(props) {
super(props); this.state = {
input_user_id: '',
};
}
deleteUser = () => { var that = this;
const { input_user_id } = this.state; db.transaction(tx => {
tx.executeSql(
'DELETE FROM  table_user where user_id=?', [input_user_id],
(tx, results) => {
console.log('Results', results.rowsAffected); if (results.rowsAffected > 0) {
Alert.alert( 'Success Alert',
'Successfully deleted User', [
{
text: 'Alright!',
onPress: () => that.props.navigation.navigate('HomeScreen'),
},
],
{ cancelable: false }
);
} else {
alert('Please mention a valid User Id');
}
}
);
});
};
render() {
return (
<View style={{ backgroundColor: '#ffffff', flex: 1 }}>
<Mytextinput
placeholder="Enter User Id"
onChangeText={input_user_id => this.setState({ input_user_id })}
style={{ padding:11 }}
/>
<Mybutton
title="Click to Delete User"
customClick={this.deleteUser.bind(this)}
/>
</View>
);
}
}

  • HomeScreen.js

import React from 'react';
import { View } from 'react-native';
import Mybutton from './pages/Custombutton'; import Mytext from './pages/Customtext';
import { openDatabase } from 'react-native-sqlite-storage'; var db = openDatabase({ name: 'UserDatabase.db' });
export default class HomeScreen extends React.Component { constructor(props) {
super(props); db.transaction(function(txn) {
txn.executeSql(
"SELECT name FROM sqlite_master WHERE type='table' AND name='table_user'",
[],
function(tx, res) {
console.log('item:', res.rows.length); if (res.rows.length == 0) {
txn.executeSql('DROP TABLE IF EXISTS table_user', []); txn.executeSql(
'CREATE TABLE IF NOT EXISTS table_user(user_id INTEGER PRIMARY KEY AUTOINCREMENT, user_name VARCHAR(20), user_contact INT(10), user_address VARCHAR(255))',
[] );
}
}
);
});
}
render() { return (
<View

  • RegisterUser.js

import React from 'react'; import { View
, ScrollView
, KeyboardAvoidingView
, Alert } from 'react-native';
import Mytextinput from './pages/Customtextinput'; import Mybutton from './pages/Custombutton';
import { openDatabase } from 'react-native-sqlite-storage';
var db = openDatabase({ name: 'UserDatabase.db' });
export default class RegisterUser extends React.Component {
constructor(props) { super(props); this.state = {
user_name: '', user_contact: '', user_address: '',
};
}
register_user = () => { var that = this;
const { user_name } = this.state; const { user_contact } = this.state; const { user_address } = this.state; if (user_name) {
if (user_contact) { if (user_address) {
db.transaction(function(tx) { tx.executeSql(
'INSERT INTO table_user (user_name, user_contact, user_address) VALUES (?,?,?)',
[user_name, user_contact, user_address], (tx, results) => {
console.log('Results', results.rowsAffected); if (results.rowsAffected > 0) {
Alert.alert( 'Success Alert',
'Your Registration is Successful', [
{
text: 'Alright!',
onPress: () =>
that.props.navigation.navigate('HomeScreen'),
},
],
{ cancelable: false }
);
} else {
alert('Registration has Failed');
}
}
);
});
} else {
alert('Please mention Address');
}
} else {
alert('Please mention Contact Number');
}
} else {
alert('Please mention Name');
}
};
render() { return (
<View style={{ backgroundColor: '#ffffff', flex: 1 }}>
<ScrollView keyboardShouldPersistTaps="handled">
<KeyboardAvoidingView behavior="padding"
style={{ flex: 1, justifyContent: 'space-between' }}>
<Mytextinput
placeholder="Enter Name here"
onChangeText={user_name => this.setState({ user_name })} style={{ padding:10 }}
/>
<Mytextinput
placeholder="Enter Contact No here"
onChangeText={user_contact => this.setState({ user_contact
})}
maxLength={10} keyboardType="numeric" style={{ padding:10 }}
/>
<Mytextinput
placeholder="Enter Address here"
onChangeText={user_address => this.setState({ user_address
})}
maxLength={225} numberOfLines={5} multiline={true}
style={{ textAlignVertical: 'top',padding:10 }}
/>
<Mybutton
title="Click to Submit" customClick={this.register_user.bind(this)}
/>
</KeyboardAvoidingView>
</ScrollView>
</View>
);
}
}

3. App.js

import React from 'react';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator} from 'react-navigation-stack';
import HomeScreen from './pages/HomeScreen'; import RegisterUser from './pages/RegisterUser'; import DeleteUser from './pages/DeleteUser';
const App = createStackNavigator({ HomeScreen: {
screen: HomeScreen, navigationOptions: {
title: 'Welcome to  HomeScreen', headerStyle: { backgroundColor: '#df36eb' }, headerTintColor: '#ffffff',
},
},
Register: {
screen: RegisterUser, navigationOptions: {
title: 'User Registration',
headerStyle: { backgroundColor: '#df36eb' }, headerTintColor: '#ffffff',
},
},
Delete: {
screen: DeleteUser, navigationOptions: {
title: 'User Deletion',
headerStyle: { backgroundColor: '#df36eb' }, headerTintColor: '#ffffff',
},
},
});
export default createAppContainer(App);

Output:

 Image1 shows the HomeScreen and Image2 shows UserRegistration Screen and Image3 and Image4 are UserDeletion Screens.

Popular Course in this category
React JS Redux Training (1 Course, 5 Projects)1 Online Courses | 5 Hands-on Projects | 18+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,496 ratings)
Course Price

View Course

Related Courses

React Native SQLite-1.1

Output-1.2

Image 1 & Image 2

 Output-1

Image 3 & Image 4

Recommended Articles

This is a guide to React Native SQLite. Here we also discuss the Introduction and how to create a SQLite database along with different examples and code implementation. You may also have a look at the following articles to learn more –

  1. React Native Charts
  2. React Native Drawer Navigation
  3. React Native Libraries
  4. React Native Image
  5. React Native Firebase

React JS Redux Training (1 Course, 4 Projects)

1 Online Courses

5 Hands-on Projects

18+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

1 Shares
Share
Tweet
Share
Primary Sidebar
React Native Tutorial
  • Basic
    • What is React Native?
    • React Versions
    • React Constructor
    • React Native Architecture
    • React Native Libraries
    • React Components Libraries
    • React Native Components
    • React Component Library
    • React Component Lifecycle
    • React Native Framework
    • React Higher Order Component
    • React Ternary Operator
    • React Native Charts
    • React Native Layout
    • React Native Grid
    • React Native Fetch
    • React Native Modal
    • React Native SVG
    • Button in React Native
    • React List Components
    • React Native Element
    • React Native FlatList
    • React Native SectionList
    • react native dropdown
    • React Native Menu
    • React Native State
    • React State Management
    • React Native Tabs
    • React Native Tab Bar
    • React Format
    • React-Native Switch
    • React Native Firebase
    • React Native Flexbox
    • React Native StatusBar
    • React Native ScrollView
    • React Native ListView
    • React Native TextInput
    • React Native Table
    • React-Native Border Style
    • React Native Search Bar
    • React-Native StyleSheet
    • React Native Vector Icons
    • React Native Login Screen
    • React Native Splash Screen
    • React Native Image Picker
    • React Native Navigation
    • React Native Swift
    • React Controlled Input
    • React Fragment
    • React Native Color
    • React Portals
    • React Refs
    • React shouldComponentUpdate()
    • React ComponentDidMount()
    • React componentWillUpdate()
    • React Native Orientation
    • React Native Animation
    • React Native Form
    • React Props
    • React Native Linear Gradient
    • React Native AsyncStorage
    • React Error Boundaries
    • React Native Progress Bar
    • React-Native Calendar
    • React Native Linking
    • React Native DatePicker
    • React Native Image
    • React Native Drawer
    • React Native Drawer Navigation
    • React Native Fonts
    • React Native Overlay
    • React Native OneSignal
    • React Native Template
    • React Native Router
    • React Router Transition
    • React Dispatcher
    • React Native Redux
    • React JSX
    • React native keyboardavoidingview
    • React Native Permissions
    • React Redux Connect
    • React Native Material
    • React Native Gesture Handler
    • React Native Theme
    • React Native Accessibility
    • React Native Justify Content
    • MobX React Native
    • React Native Authentication
    • React Native UUID
    • React Native Geolocation
    • React Native Debugger
    • React Native Carousel
    • React Native Local Storage
    • React Native TypeScript
    • React Bootstrap
    • React Native SQLite
    • React Native Interview Questions
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - React JS Redux Training (1 Course, 4 Projects) Learn More