Updated April 3, 2023
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.
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.
Image 1 & Image 2
Image 3 & Image 4
Recommended Articles
This is a guide to React Native SQLite. Here we also discuss the Introduction and how to create an SQLite database along with different examples and code implementation. You may also have a look at the following articles to learn more –