Categories
React-Native

Simple React-Native Form Example

Here, we are going to prepare a simple app which posts name and surname data to our php endpoint.

You may want to check Simple React Form Example to learn how to prepare a SQLite database which suits our needs.

Here our php endpoint Endpoint.php . We are using a SQLite database called my.db

<?php
header("Access-Control-Allow-Origin: *");

error_reporting(0);

$name = $_POST['name'];
$surname = $_POST['surname'];

if (!empty($name) && !empty($surname)) {
$db = new SQLite3('my.db');
$db->exec("INSERT INTO names VALUES ('$name','$surname')");
echo "done";
}
else {
echo "name or surname is empty";
}

Now React Native part. App.js

Note that it uses native-base components for UI. You may want to check my previous posts to learn how to install native-base.

import React, { Component } from 'react';
import { Container, Header, Content, Input, Item, Form, Button, Text } from 'native-base';

export default class App extends Component{
  constructor(props) {
    super(props);

    this.state = {name: '', surname: ''};
    this.handleNameChange = this.handleNameChange.bind(this);
    this.handleSurnameChange = this.handleSurnameChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleNameChange(name) {
    this.setState({name: name});
  }

  handleSurnameChange(surname) {
    this.setState({surname: surname});
  }

  handleSubmit() {    
      fetch('http://******IP_ADDRESS_HERE******/endpoint.php', { 
        method: 'POST',
        mode: 'cors',
        cache: 'no-cache',
        headers: {
          'Content-Type' : 'application/x-www-form-urlencoded',
        },
        body: "name=" + this.state.name + "&surname=" + this.state.surname,
        }).then((res)=> console.log(res)).catch((error) => console.error(error));
  }
  
  render() {
   return (
    <Container>
    <Header />
    <Content>
      <Form onSubmit={this.handleSubmit}>
        <Item>
          <Input placeholder="Name" onChangeText={this.handleNameChange} />
        </Item>
        <Item last>
          <Input placeholder="Surname" onChangeText={this.handleSurnameChange} />
        </Item>
          <Button onPress={this.handleSubmit}><Text>Save</Text></Button>
      </Form>
    </Content>
  </Container>
   );
 }
}

Change IP_ADDRESS_HERE with your target IP. Note that, it will not allow HTTP addresses in production release, so you need to set up HTTPS.