Friday, May 29, 2020

React Native Part 6: Adding Item to List (Code Snippet)


import React, { useState } from 'react';
import {
  StyleSheet,
  Text,
  View,
  TextInput,
  Button,
  ScrollView,
  FlatList
} from 'react-native';

export default function App() {
  const [enteredContact, setEnteredContact] = useState('');
  const [contacts, setContacts] = useState([]);

  const contactInputHandler = enteredText => {
  setEnteredContact(enteredText);
  };

  const addContactHandler = () => {
    setContacts(contacts => [
      ...contacts,
      { id: Math.random().toString(), text: enteredContact }
    ]);
  };

  return (
    <View style={styles.screen}>
      <View style={styles.inputContainer}>
        <TextInput
          placeholder="Course Contact"
          style={styles.input}
          onChangeText={contactInputHandler}
          value={enteredContact}
        />
        <Button title="ADD" onPress={addContactHandler} />
      </View>
      <FlatList
        keyExtractor={(item, index) => item.id}
        data={contacts}
        renderItem={itemData => (
          <View style={styles.listItem}>
            <Text>{itemData.item.text}</Text>
          </View>
        )}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  screen: {
    padding: 50
  },
  inputContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center'
  },
  input: {
    width: '80%',
    borderColor: 'black',
    borderWidth: 1,
    padding: 10
  },
  listItem: {
    padding: 10,
    marginVertical: 10,
    backgroundColor: '#ccc',
    borderColor: 'black',
    borderWidth: 1
  }
});


No comments:

Post a Comment