Feliks_JS
Feliks_JS

Reputation: 81

How to get the value ot TextInput and add to Flatlist in React Native

I want to get the value of TextInput and add to my flatList: here is my TextInput


        <TextInput style={styles.input}
          underlineColorAndroid="transparent"
          placeholder="   Money "
          placeholderTextColor="#9a73ef"
          autoCapitalize="none"
          keyboardType='numeric'
          value = 'money'
        />

This is my Button that will add the value of TextInput into my Flatlist

 <Button
          title="Add me"
          color="#841584"
          accessibilityLabel="Learn more about this purple button"
        />

        <FlatList
          data={DATA}
          renderItem={({ item }) => (<Text style = {styles.item}> {item.name}</Text>)} />


    </View>

Upvotes: 1

Views: 1084

Answers (2)

Feliks_JS
Feliks_JS

Reputation: 81

just added

 <FlatList
          data={data}
          renderItem={({ item }) => (<Text style = {styles.item}> {item.name}</Text>)}
          keyExtractor={(item, index) => index.toString()}  
           />

it worked

Upvotes: 0

Ketan Ramteke
Ketan Ramteke

Reputation: 10665

enter image description here

Working Example: Expo Snack

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

export default function App() {
  const [data, setData] = useState([{ name: 'ketan' }]);
  const [name, setName] = useState('');
  return (
    <View style={styles.container}>
      <TextInput
        style={{ backgroundColor: 'white', padding: 10, marginTop: 10 }}
        onChangeText={(name) => setName(name)}
        placeholder={'enter name'}
        value={name}
      />
      <Button
        title={'add me'}
        onPress={() => {
          if (name) setData([...data, { name: name }]);
          console.log('hi');
        }}
      />
      <FlatList
        keyExtractor={(item) => item}
        data={data}
        renderItem={({ item }) => <Text>{item.name}</Text>}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
});

Upvotes: 2

Related Questions