Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

list in react native

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

function ListStuff(){
	const [listInput, setListInput] = useState("");
    const [listData, setListData] = useState<{
    	myKey: string;
    }>([]);
  	const [error, setError] = useState("");
  
  	const addInputDataToList = ()=>{
    	if(listInput === ""){
        	setError("input can not be empty");
          	return;
        }
      	const newListData = [...listData, {myKey: listInput}];
      	setListData(newListData);
      	setError("");
      	setListInput("");
    };
  
  	return(
    	<View style={styles.view}>
            <Text> Input </Text>
	        <TextInput value={listInput} style={styles.input} onChangeText={setListInput} />
			<Button title="add" onPress={addInputDataToList} />
              
      		<Text> List </Text>
			<ScrollView>
              <FlatList 
				style={styles.list}
				keyExtractor={item => item.myKey} 
				data={listData}
				renderItem={({item})} => (
                	<Text style={styles.item}> {item.file} </Text>
                )}
              />
			</ScrollView>
			{error && <Text>{error}</Text>}
		</View>
	);
}
export default ListStuff;

const styles = StyleSheet.create({
  input: {
    height: 40,
    width: 200,
    margin: 12,
    borderWidth: 1,
    padding: 10,
  },
  view: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
  list: {
    flex: 1,
    margin: 10,
  },
  item: {
    padding: 3,
    fontSize: 14,
    height: 22,
  },

});
 
PREVIOUS NEXT
Tagged: #list #react #native
ADD COMMENT
Topic
Name
1+8 =