AppDividend
Latest Code Tutorials

React Native Create Delete Functionality From Scratch

592

Get real time updates directly on you device, subscribe now.

React Native Create Delete Functionality From Scratch is today’s leading topic. We build a simple functionality where users can add and remove places client side. It does not affect the server side because there is no backend. But you will learn how you can create simple clientside create and delete the data in the application. We will test both on Android and iOS Simulators. So to get started, React Native Create Delete Functionality. Let us started.

React Native Create Delete Functionality

We start our project by installing React Native CLI globally on the Mac. You can skip the following command if you have already installed.

#1: Install React Native.

Type the following command.

npm install -g react-native-cli

Okay, now for creating a new application, type the following command.

react-native init rncreate

 

React Native Create Delete Functionality From Scratch

Now, after installing, we need to open this application in the two different Simulators.

For testing on iOS simulator, type the following command.

react-native run-ios

If you have configured XCode correctly, then one iOS device will pop up as well as development server will also start.

React Native Simulator

 

To open the project inside Android device type the following command.

react-native run-android

Also, you need to install Android Studio and then create a virtual device.

If you have found the error like following.

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ‘:app‘.
> SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable.

Then the solution is the following.

Inside the Android folder, create a new file called local.properties and add the following code. Here, you can use your username, and I am using Mac.

sdk.dir = /Users/your username/Library/Android/sdk

Now, again run the above command and shall fix the problem.

React Native Create Delete Functionality

 

 

You can also use an expo for this application. If you do not know anything about the expo, then please check out my this How To Setup React Native Using Expo.

#2: Add Textbox and Button into the App.js.

Okay, so we will add a text box and button to add places. So let us add the TextInput and Button.  Also, we will add flexbox layout. Write the following code inside the App.js file.

Related Posts
1 of 8
// App.js

import React, {Component} from 'react';
import { StyleSheet, View, TextInput, Button } from 'react-native';

export default class App extends Component {

placeSubmitHandler = () => {
    console.log("Submitted");	
}

render() {
   return (
	<View style={ styles.container }>
	   <View style = { styles.inputContainer }>
		<TextInput
		   placeholder = "Seach Places"
		   style = { styles.placeInput }
		></TextInput>
		<Button title = 'Add' 
			style = { styles.placeButton }
			onPress = { this.placeSubmitHandler }
		/>
	    </View>
	</View>
    );
  }
}

const styles = StyleSheet.create({
	  container: {
    	  paddingTop: 30,
    	  justifyContent: 'flex-start',
    	  alignItems: 'center',
      },
      inputContainer: {
	  flexDirection: 'row',
	  justifyContent: 'space-between',
	  alignItems: 'center',
	  width: '100%'
      },
      placeInput: {
	  width: '70%'
      },
      placeButton: {
	  width: '30%'
      }
});

Here is the output on both of the devices.

React Native CRUD Tutorial

 

#3: Define the state and input handler.

Okay, now we need a state to manage. So we define the initial state like following.

// App.js

state = {
   placeName: '',
   places: []
}

placeSubmitHandler = () => {
    console.log("Submitted");	
}

So, we have taken placeName to display the value inside text input and places array on which we loop through and show all the places in FlatList.

// App.js

import React, {Component} from 'react';
import { StyleSheet, View, TextInput, Button } from 'react-native';

export default class App extends Component {

state = {
    placeName: '',
    places: []
}

placeSubmitHandler = () => {
    if(this.state.placeName.trim() === '') {
	return;
    }
    this.setState(prevState => {
      return {
	        places: prevState.places.concat({
		key: Math.random(), 
		value: prevState.placeName
	   })
       }
   });	
}

placeNameChangeHandler = (value) => {
  this.setState({
      placeName: value
    });    
}

render() {
   return (
	<View style={ styles.container }>
	   <View style = { styles.inputContainer }>
		<TextInput
		   placeholder = "Seach Places"
		   style = { styles.placeInput }
                   value = { this.state.placeName }
		   onChangeText = { this.placeNameChangeHandler }
		></TextInput>
		<Button title = 'Add' 
		   style = { styles.placeButton }
		   onPress = { this.placeSubmitHandler }
		/>
	    </View>
	</View>
    );
  }
}

So, when you start typing inside TextInput, the state is updated, and you can see the values inside text input, and when you press the add button, it checks if the value is empty or not. If not empty then add the values inside places array. It is a very familiar practice in React.js.

#4: Display the Data in the FlatList.

Inside root, create one folder called components and inside create one file called ListItem.js and add the following code inside that file.

// ListItem.js

import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';

const ListItem = (props) => {
    return (
        <TouchableOpacity>
            <View style = { styles.listItem }>
                <Text>{ props.placeName }</Text>
            </View>
        </TouchableOpacity>
    );
}

const styles = StyleSheet.create({
    listItem: {
        width: '100%',
        padding: 10,
        marginBottom: 10,
        backgroundColor: '#eee'
    }
});

export default ListItem;

We have created this file because we will render this component and display the list. Here, we have passed the props as an argument, so we can access the place values through props and display it in the proper format.

Okay, now we need to include the FlatList inside App.js file and render the above component.

// App.js

import React, {Component} from 'react';
import { StyleSheet, View, TextInput, Button, FlatList } from 'react-native';
import ListItem from './components/ListItem';

export default class App extends Component {

state = {
    placeName: '',
    places: []
}

placeSubmitHandler = () => {
    if(this.state.placeName.trim() === '') {
	return;
    }
    this.setState(prevState => {
      return {
	        places: prevState.places.concat({
		key: Math.random(), 
		value: prevState.placeName
	   })
       }
   });
   this.setState({
      placeName: ''
   });	
}

placeNameChangeHandler = (value) => {
  this.setState({
      placeName: value
    });    
}

placesOutput = () => {
   return (
	<FlatList style = { styles.listContainer }
	   data = { this.state.places }
	   keyExtractor={(item, index) => index.toString()}
           renderItem = { info => (
		  <ListItem 
		        placeName={ info.item.value }
		   />
	     )}
	/>
    )
}

render() {
   return (
	<View style={ styles.container }>
	   <View style = { styles.inputContainer }>
		<TextInput
		   placeholder = "Seach Places"
		   style = { styles.placeInput }
                   value = { this.state.placeName }
		   onChangeText = { this.placeNameChangeHandler }
		></TextInput>
		<Button title = 'Add' 
		   style = { styles.placeButton }
		   onPress = { this.placeSubmitHandler }
		/>
	    </View>
            <View style = { styles.listContainer }>
		{ this.placesOutput() }
	    </View>
	</View>
    );
  }
}

const styles = StyleSheet.create({
      container: {
    	  paddingTop: 30,
    	  justifyContent: 'flex-start',
    	  alignItems: 'center',
      },
      inputContainer: {
	  flexDirection: 'row',
	  justifyContent: 'space-between',
	  alignItems: 'center',
	  width: '100%'
      },
      placeInput: {
	  width: '70%'
      },
      placeButton: {
	  width: '30%'
      },
      listContainer: {
	  width: '100%'
      }
});

 

React Native FlatList ScrollView Example

#5: Implement Delete Functionality.

So, when the user touches the list, it will remove the element from an array. We have already used the TouchableOpacity. So it fades the particular item and removes from the list permanently.

For that, we need to add the onPress() event to the TouchableOpacity. So we can pass the index value and filter out the data based on that index.

So, we need to add the event inside first App.js file, and then through props, we can access that inside ListItem.js file.

// App.js

import React, {Component} from 'react';
import { StyleSheet, View, TextInput, Button, FlatList } from 'react-native';
import ListItem from './components/ListItem';

export default class App extends Component {

state = {
    placeName: '',
    places: []
}

placeSubmitHandler = () => {
    if(this.state.placeName.trim() === '') {
	return;
    }
    this.setState(prevState => {
      return {
	        places: prevState.places.concat({
		key: Math.random(), 
		value: prevState.placeName
	   })
       }
   });
   this.setState({
      placeName: ''
   });	
}

placeNameChangeHandler = (value) => {
  this.setState({
      placeName: value
    });    
}

placesOutput = () => {
   return (
	<FlatList style = { styles.listContainer }
	   data = { this.state.places }
	   keyExtractor={(item, index) => index.toString()}
           renderItem = { info => (
		  <ListItem 
		        placeName={ info.item.value }
                        onItemPressed={() => this.onItemDeleted(info.item.key)}
		   />
	     )}
	/>
    )
}

onItemDeleted = (key) => {
   this.setState(prevState => {
      return {
         places: prevState.places.filter(place => {
            return place.key !== key;
	  })
	}
    })
}

render() {
   return (
	<View style={ styles.container }>
	   <View style = { styles.inputContainer }>
		<TextInput
		   placeholder = "Seach Places"
		   style = { styles.placeInput }
                   value = { this.state.placeName }
		   onChangeText = { this.placeNameChangeHandler }
		></TextInput>
		<Button title = 'Add' 
		   style = { styles.placeButton }
		   onPress = { this.placeSubmitHandler }
		/>
	    </View>
            <View style = { styles.listContainer }>
		{ this.placesOutput() }
	    </View>
	</View>
    );
  }
}

const styles = StyleSheet.create({
      container: {
    	  paddingTop: 30,
    	  justifyContent: 'flex-start',
    	  alignItems: 'center',
      },
      inputContainer: {
	  flexDirection: 'row',
	  justifyContent: 'space-between',
	  alignItems: 'center',
	  width: '100%'
      },
      placeInput: {
	  width: '70%'
      },
      placeButton: {
	  width: '30%'
      },
      listContainer: {
	  width: '100%'
      }
});

Okay, so we have defined the onDeleteItem() function, and also we have passed that as props to the Child Element. Now, we need to modify the ListItem.js component.

// ListItem.js

import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';

const ListItem = (props) => {
    return (
        <TouchableOpacity onPress={ props.onItemPressed }>
            <View style = { styles.listItem }>
                <Text>{ props.placeName }</Text>
            </View>
        </TouchableOpacity>
    );
}

const styles = StyleSheet.create({
    listItem: {
        width: '100%',
        padding: 10,
        marginBottom: 10,
        backgroundColor: '#eee'
    }
});

export default ListItem;

Here, we have defined the onPress event. So when the user presses the list item, it will get filtered out.

So, we have a working demo of React Native Create Delete Functionality. Thanks for taking.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.