React Native Expo Login/Register dengan PHP database Mysql
Halo teman-teman, kembali ke tutorial pemrograman kita kali ini.
Bagi teman-teman yang baru mengenal React native, ada baiknya membaca artikel Mengenal React, React Native, Bare React Native, dan Expo terlebih dahulu
Kali ini kita akan membahas pembuatan aplikasi mobile menggunakan react native dengan framework Expo dan menyimpan data menggunakan API php dan database mysql.
Ketik perintah berikut untuk menginstall expo-cli dan membuat project baru usermanager-app
npm install --global expo-cli
expo init usermanager-app
Struktur file project
App.js
–pages/home.js
–pages/profile.js
–pages/login.js
–pages/register.js
React Native Source Code:
1. Apps.js
File Apps.js merupakan file utama yang berisikan navigasi ke semua halaman untuk aplikasi login dan register ini.
import React, { Component } from 'react';
import {
AppRegistry,
View,
Text,
StyleSheet,
ScrollView,
TouchableOpacity,
} from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import HomeScreen from './pages/home';
import Login from './pages/login';
import Register from './pages/register';
import Profile from './pages/profile';
const Stack = createStackNavigator();
const App = () => {
return (
<View style={{ flex: 1 }}>
<NavigationContainer>
<Stack.Navigator
screenOptions={{
// headerShown: false, // if not gonna show header
}}
>
<Stack.Screen name="HomeScreen" component={HomeScreen} />
<Stack.Screen name="Login" component={Login} />
<Stack.Screen name="Register" component={Register} />
<Stack.Screen name="Profile" component={Profile} />
</Stack.Navigator>
</NavigationContainer>
</View>
);
};
export default App;
2. Home.js
File home.js menampilkan 2 menu sederhana yaitu Login dan Register, user harus melakukan Register terlebih dahulu sebelum ke menu Login
import React, { Component } from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
export default class Home extends Component {
render() {
const { navigate } = this.props.navigation;
return (
<View style={styles.container}>
<Text style={styles.pageName}>User Manager</Text>
<TouchableOpacity onPress={() => navigate('Login')} style={styles.btn1}>
<Text style={styles.btnText}>Login</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => navigate('Register')}
style={styles.btn2}>
<Text style={styles.btnText}>Register</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
btn1: {
backgroundColor: 'orange',
padding: 10,
margin: 10,
width: '95%',
},
btn2: {
backgroundColor: 'blue',
padding: 10,
margin: 10,
width: '95%',
},
pageName: {
margin: 10,
fontWeight: 'bold',
color: '#000',
textAlign: 'center',
},
btnText: {
color: '#fff',
fontWeight: 'bold',
},
});
3. Login.js
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity,
TextInput,
Keyboard,
} from 'react-native';
export default class Login extends Component {
constructor(props) {
super(props);
this.state = {
userEmail: '',
userPassword: '',
};
}
login = () => {
const { userEmail, userPassword } = this.state;
let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (userEmail == '') {
//alert("Please enter Email address");
this.setState({ email: 'Please enter Email address' });
} else if (reg.test(userEmail) === false) {
//alert("Email is Not Correct");
this.setState({ email: 'Email is Not Correct' });
return false;
} else if (userPassword == '') {
this.setState({ email: 'Please enter password' });
} else {
fetch('https://hardeepwork.000webhostapp.com/react/login.php', {
method: 'post',
header: {
Accept: 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify({
// we will pass our input data to server
email: userEmail,
password: userPassword,
}),
})
.then((response) => response.json())
.then((responseJson) => {
if (responseJson == 'ok') {
// redirect to profile page
alert('Successfully Login');
this.props.navigation.navigate('Profile');
} else {
alert('Wrong Login Details');
}
})
.catch((error) => {
console.error(error);
});
}
Keyboard.dismiss();
};
render() {
return (
<View style={styles.container}>
<Text style={{ padding: 10, margin: 10, color: 'red' }}>
{this.state.email}
</Text>
<TextInput
placeholder="Enter Email"
style={{ width: 200, margin: 10 }}
onChangeText={(userEmail) => this.setState({ userEmail })}
/>
<TextInput
placeholder="Enter Password"
style={{ width: 200, margin: 10 }}
onChangeText={(userPassword) => this.setState({ userPassword })}
/>
<TouchableOpacity
onPress={this.login}
style={{
width: 200,
padding: 10,
backgroundColor: 'magenta',
alignItems: 'center',
}}>
<Text style={{ color: 'white' }}>Login</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});
4. Register.js
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TextInput,
TouchableOpacity,
} from 'react-native';
export default class Register extends Component {
constructor(props) {
super(props);
this.state = {
userName: '',
userEmail: '',
userPassword: '',
};
}
userRegister = () => {
const { userName } = this.state;
const { userEmail } = this.state;
const { userPassword } = this.state;
fetch('https://hardeepwork.000webhostapp.com/react/register.php', {
method: 'post',
header: {
Accept: 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify({
name: userName,
email: userEmail,
password: userPassword,
}),
})
.then((response) => response.json())
.then((responseJson) => {
alert(responseJson);
})
.catch((error) => {
console.error(error);
});
};
render() {
return (
<View style={styles.container}>
<TextInput
placeholder="Enter Name"
style={{
width: 250,
margin: 10,
borderColor: '#333',
borderWidth: 1,
}}
underlineColorAndroid="transparent"
onChangeText={(userName) => this.setState({ userName })}
/>
<TextInput
placeholder="Enter Email"
style={{
width: 250,
margin: 10,
borderColor: '#333',
borderWidth: 1,
}}
underlineColorAndroid="transparent"
onChangeText={(userEmail) => this.setState({ userEmail })}
/>
<TextInput
placeholder="Enter Password"
style={{
width: 250,
margin: 10,
borderColor: '#333',
borderWidth: 1,
}}
underlineColorAndroid="transparent"
onChangeText={(userPassword) => this.setState({ userPassword })}
/>
<TouchableOpacity
onPress={this.userRegister}
style={{
width: 250,
padding: 10,
backgroundColor: 'magenta',
alignItems: 'center',
}}>
<Text style={{ color: '#fff' }}>Signup</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});
5. Profile.js
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default class Profile extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.pageName}>Profile</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
pageName: {
margin: 10,
fontWeight: 'bold',
color: '#000',
textAlign: 'center',
},
});
API Server
1. Mysql Tabel
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(200) DEFAULT NULL,
`email` varchar(100) DEFAULT NULL,
`password` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
2. config.php
<?php
$mysqli = mysqli_connect("localhost", "testingdb", "test", "test@123");
// Check connection
if (mysqli_connect_errno()) {
// echo "Failed to connect to MySQL: " . mysqli_connect_error();
echo json_encode(array('err' => true, 'msg' => mysqli_connect_error()));
}
3. register.php
<?php include 'config.php';
$json = file_get_contents('php://input');
// decoding the received JSON and store into $obj variable.
$obj = json_decode($json, true);
// name store into $name.
$name = $obj['name'];
// same with $email.
$email = $obj['email'];
// same with $password.
$password = $obj['password'];
if ($obj['email'] != "") {
// $result= $mysqli->query("SELECT * FROM users where email='$email'");
$query = sprintf(
"SELECT * FROM users WHERE email= '%s' limit 1",
$mysqli->real_escape_string($email)
);
$result = $mysqli->query($query);
if ($result->num_rows > 0) {
echo json_encode('email already exist'); // alert msg in react native
} else {
// $add = $mysqli->query("insert into users (name,email,password) values('$name','$email','$password')");
$query = sprintf(
"insert into users (name,email,password) values('%s','%s','%s')",
$mysqli->real_escape_string($name),
$mysqli->real_escape_string($email),
$mysqli->real_escape_string($password)
);
$result = $mysqli->query($query);
if ($add) {
echo json_encode('User Registered Successfully'); // alert msg in react native
} else {
echo json_encode('check internet connection'); // our query fail
}
}
} else {
echo json_encode('try again');
}
4. login.php
<?php include 'config.php';
$json = file_get_contents('php://input');
$obj = json_decode($json, true);
$email = $obj['email'];
$password = $obj['password'];
if ($obj['email'] != "") {
// $result= $mysqli->query("SELECT * FROM users where email='$email' and password='$password'");
$query = sprintf(
"SELECT * FROM users WHERE email= '%s' and password='%s' limit 1",
$mysqli->real_escape_string($email),
$mysqli->real_escape_string($password)
);
$result = $mysqli->query($query);
if ($result->num_rows == 0) {
echo json_encode('Wrong Details');
} else {
echo json_encode('ok');
}
} else {
echo json_encode('try again');
}
Snack Expo Link : https://snack.expo.dev/@rudiahmad/usermanager-login-register-form-with-mysql-php-json
Github : https://github.com/rudiahmad/UserManager-Login-Register-Form-with-Mysql-PHP-json
Project di atas di forked dari sumber di bawah ini dengan menggunakan expo dan react native versi terbaru
I am completely new to React Native and I am seeking to develop a mobile version of my existing website. I wish all those seeking to help beginners would appreciate that database access is absolutely basic to virtually any application. I was thus delighted to see this example. Unfortunately, it falls short of really helping. It makes reference to react-navigation “imports” which, it seems, is not integral to RN. So, I can’t get the example to run. A more detailed explanation of the required environment would have been more helpful.