Description
From the sample code below, the FlatList returns n-number of TextInput, when a value is entered on a particular TextInput it keeps re-rendering every other TextInput.
Sample Code
<FlatList
...........
renderItem ={this.renderItem}
/>
renderItem=(item)=>{
<Text>{item.name}</Text>
<TextInput
.........
onChangeText ={(text)=>this.setState({text})}
value={this. state.text}
/>
}
Solution
I have tried to assign a key to the TextInput but don't know how to go avout it
Update: Added Complete Example
You need to maintain textinputs state as an array to store the values for each textinput
import React, { Component } from 'react';
import {
View,
Text,
FlatList,
TouchableOpacity,
TextInput,
} from 'react-native';
export class Demo extends Component {
state = {
textInputs: [],
};
render() {
return (
<View style={{ flex: 1, marginTop: 20 }}>
<FlatList
style={{ flex: 1 }}
data={[1, 2, 3, 4, 5]}
renderItem={({ item, index }) => {
return (
<View
style={{
height: 100,
backgroundColor: '#F0F0F0',
width: 300,
alignSelf: 'center',
margin: 10,
}}
>
<TextInput
style={{
flex: 1,
backgroundColor: '#C0C0C0',
}}
onChangeText={text => {
let { textInputs } = this.state;
textInputs[index] = text;
this.setState({
textInputs,
});
}}
value={this.state.textInputs[index]}
/>
<TouchableOpacity
style={{
backgroundColor: 'red',
flex: 1,
alignItems: 'center',
justifyContent: 'center',
}}
onPress={() => {
let { textInputs } = this.state;
textInputs[index] = '';
this.setState({
textInputs,
});
}}
>
<Text> Clear</Text>
</TouchableOpacity>
</View>
);
}}
/>
</View>
);
}
}
Just remove value attribute from your TextInput, but this is not the solution as the value is stores into single state only, so if you want to get value of multiple textinputs you have to create rowrender and array of states
<TextInput
.........
onChangeText ={(text)=>this.setState({text})}
//value={this. state.text}
/>
Related
I have stored the value locally using array, And I want to delete a single item by using Trash icon. But I need to delete the multi selected items from the array.
So I placed the button "Delete selected". But I am not able to select multiple items and I don't know how to write the functionality to delete multiple items. I'm new for the React Native so kindly help.
Here is my code
import React, { Component } from "react"
import { View, Text, TouchableOpacity, TouchableHighlight, TextInput, StyleSheet, FlatList,onRemove } from 'react-native'
import {Card,CardItem,Right} from 'native-base';
import Swipeout from 'react-native-swipeout'
import Icon from 'react-native-vector-icons/FontAwesome';
import MultiSelect from 'react-native-multiple-select';
class Screen3 extends Component{
constructor(props) {
super(props);
this.state = {
loading: false,
firstname:[],
onPress:true,
unique1:[],
unique:[],
selectedItems : [],
renderData:item,
key1:0
};
}
componentDidMount=()=>{
const{navigation}=this.props
const data=navigation.getParam('data','')
const unique=data.filter((value,index,self)=>self.indexOf(value)===index)
var key=0
const unique1=[]
for(var i=0;i<unique.length;i++){
key=key+1
var result={"name":unique[i],"key":key}
this.state.unique1.push(result)
this.state.key1=this.state.key1+1
this.setState({key1:this.state.key1})
}
}
onPressHandler(item) {
let renderData=[...this.state.renderData];
for(let data of renderData){
if(data.item==item){
data.selected=(data.selected==null)?true:!data.selected;
break;
}
}
this.setState({renderData});
}
deleteItem = (item,index) => {
console.log(item.name,index)
this.state.unique=this.state.unique1
let filtered=this.state.unique.filter((item1) => item1.key !== item.key)
console.log(filtered)
this.setState({unique1:filtered})
}
render(){
return (
<View>
<Text style={styles.heading}>
Manage Screen
</Text>
<TouchableOpacity style = {styles.Button}
onPress={()=>this.deleteItem(item,index) } >
<Text style={styles.button}>Delete selected</Text>
</TouchableOpacity>
<FlatList
data={this.state.unique1}
showsVerticalScrollIndicator={false}
extraData={this.state.key1}
style={{ marginTop: 16 }}
renderItem={({ item, index }) => (
// <TouchableOpacity onPress={() => this.handleData(item)}>
<TouchableOpacity onPress={() => this.onPressHandler(item,index)}>
item!=null?
<Card
style={{
elevation: 10,
marginBottom: 15,
}}
>
<View style={{ flex: 1 }}></View>
<CardItem bordered >
style={
item.selected==true
? {
padding: 10,
borderRadius: 5,
backgroundColor: '#000000',
}
: {
borderRadius: 5,
backgroundColor: '#a1a1a1',
}}
<Text>{item.name}</Text>
<Right style={{alignSelf:'flex-end' } }>
<TouchableOpacity onPress={() => this.deleteItem(item,index)}>
<Icon size={25} name={Platform.OS ==='android' ? "trash" : "ios-trash"} color="red"/>
</TouchableOpacity>
</Right>
</CardItem>
</Card>:null
// </TouchableOpacity>
)
}
/>
</View>
)
}
}
export default Screen3
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
heading: {
fontSize: 23,
paddingVertical:80,
textAlign: 'center',
marginBottom: 30,
marginTop: -40,
},
button:{
width:('39%'),
height:('4%'),
alignItems:'center',
borderWidth:1,
borderRadius:2,
marginTop:-80,
marginHorizontal:10,
marginLeft:110,
justifyContent:'center',
backgroundColor: '#b0c4de',
padding: 9,
fontSize: 15,
margin: 15,
height: 40,
width: 160,
alignItems: 'center'
}
}
)
You would need a different function to delete multiple items and that function would call your deleteItem() function. A simple, but not so efficient way would be to loop through your selectedItems and find them in your data array and then remove each selected item with deleteItem(). You can then improve from there if it's not efficient enough.
I'm quite new to react native and trying to set up a search bar with search functionality. I'm trying to set it up where the list updates with each letter typed. The data is displayed fine but the error occurs when I try and type something into the search bar.
Full Error Message
https://ibb.co/Zd5hB52
Here is the file that is having issues
import { StyleSheet, Text, View, Button, StatusBar, ScrollView, TextInput } from "react-native";
import Icon from 'react-native-vector-icons/Ionicons';
import datas from "../components/CurrencyData"
import FavouritesList from "../components/FavouritesList";
const AddToFavourites = () => {
const state = {
datas: datas,
filter: datas
}
const [currencyFilter, setSearch] = useState(state.filter)
const getFlags = () => {
return currencyFilter.map(data => {
return <FavouritesList detail={data} key={data.id}/>
})
}
const searchCurrencies = (searchFor) => {
setSearch({
filterCurrency: datas.filter(i=>
i.name.toLowerCase().includes(searchFor.toLowerCase),
),
});
}
return (
<View style={styles.container}>
<View style= {styles.action}>
<Icon name="search" size={25}/>
<TextInput
style= {{flex: 1}}
placeholder= "Search..."
underlineColorAndroid="transparent"
onChangeText= {text => {searchCurrencies(text)}}
/>
</View>
<ScrollView>
<StatusBar backgroundColor="#1E90FF" barStyle="light-content"/>
{getFlags()}
</ScrollView>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center",
},
action: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
borderWidth: 2,
height: 50,
borderRadius: 30,
paddingLeft: "4%",
paddingRight: "4%",
margin: "3%"
},
})
export default AddToFavourites;```
[1]: https://i.stack.imgur.com/kWkHo.png
with hooks you don't pass the state object like setState, you just pass the new value
change
setSearch({
filterCurrency: datas.filter(i => i.name.toLowerCase().includes(searchFor.toLowerCase)),
});
to
setSearch( datas.filter(I =>i.name.toLowerCase().includes(searchFor.toLowerCase)));
I have this code, where on ChangeText in react native, i am inserting multiple field values in the state, item. For some reason, the output in the console log shows alphabetical order. Since the logic is, that on ChangText, the function EnterValue inserts the value in item state. it finds the property name and then matches that to the text value, I think something gets wrong along the way. Please see below the code
import { StatusBar } from "expo-status-bar";
import React from "react";
import { StyleSheet, Text, View, Button, TextInput } from "react-native";
class App extends React.Component {
constructor() {
super();
this.state = {
step: 1,
TotalItem: [],
item: {
Brand: null,
Quantity: null,
Instructions: null,
},
};
}
// remember this logig since take names, it adds property values in alphabetical order, and thus change the order
EnterValue = (name) => {
return (text) => {
this.setState((prevState) => ({
item: { ...prevState.item, [name]: text },
}));
};
};
submit = (e) => {
e.preventDefault(e);
const { step } = this.state;
this.setState({
step: step + 1,
});
this.setState(
{
TotalItem: [...this.state.TotalItem, this.state.item],
},
() => {
console.log("updated state", this.state.TotalItem);
}
);
};
render() {
return (
<View style={{ flex: 1, margin: 20 }}>
<TextInput
placeholder="enter name"
onChangeText={this.EnterValue("Brand")}
style={{ borderWidth: 2, borderColor: "skyblue", margin: 20 }}
/>
<TextInput
placeholder="Quantity"
onChangeText={this.EnterValue("Quantity")}
style={{ borderWidth: 2, borderColor: "skyblue", margin: 20 }}
/>
<TextInput
placeholder="Instructions"
onChangeText={this.EnterValue("Instructions")}
style={{ borderWidth: 2, borderColor: "skyblue", margin: 20 }}
/>
<View style={styles.container}>
<View style={{ flex: 1 }}>
<Button
style={{ flex: 1, backgroundColor: "red" }}
title="add"
onPress={this.add}
/>
</View>
<View style={{ flex: 1 }}>
<Button
style={{ flex: 1, backgroundColor: "blue" }}
title="submit"
onPress={this.submit}
/>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
},
});
export default App;
Change
onChangeText={this.EnterValue("Quantity")}
onChangeText={this.EnterValue("Brand")}
onChangeText={this.EnterValue("Instructions ")}
To
onChangeText={() => this.EnterValue("Quantity")}
onChangeText={() => this.EnterValue("Brand")}
onChangeText={() => this.EnterValue("Instructions ")}
I have a ScrollView component, and within it I have a form (<AppForm >) that works using Formik and Yup. This form has some input fields (<AppTextInput >). In the form I assign the keyboardType prop for each input field.
The problem is that the fields with keyboardType set to default scroll down the whole ScrollView component when you focus on it, like adding margin to the top of it. This only happens when the keyboardType is set to default.
If I focus on an input field with the keyboardType prop set to numeric, everything works fine.
Any idea of what am I doing wrong?
Here is a gif of what's exactly the problem:
https://giphy.com/gifs/djoHUBAKu9XGyu37OO
And here is my code:
AppFormField (Main screen)
function ActivityFormScreen({ navigation }) {
return (
<View style={styles.container}>
<ActivityIndicator
visible={
postActivityApi.loading ||
editActivityApi.loading ||
getTrabajosApi.loading ||
getCosechasApi.loading ||
getMaquinariasApi.loading
}
/>
<ScrollView style={{ paddingBottom: 500 }}>
<ActivityTitle
text="InformaciĆ³n"
name="information-variant"
size={35}
/>
<AppForm
onSubmit={(form) => handleSubmit(form)}
validationSchema={validationShema}
initialValues={{
fecha: getFormValue("fecha"),
finca_id: getFormValue("finca_id"),
lote: getFormValue("lote"),
cosecha: getFormValue("cosecha"),
cultivos: getFormValue("cultivos"),
maquinaria: getFormValue("maquinaria"),
tiempo_actividad: getFormValue("tiempo_actividad"),
productos: getFormValue("productos"),
cantidad: getFormValue("cantidad"),
unidad: getFormValue("unidad"),
hectarea_trabajada: getFormValue("hectarea_trabajada"),
trabajos: getFormValue("trabajos"),
observaciones: getFormValue("observaciones"),
}}
>
<AppFormField
name="fecha"
holder="Fecha"
keyboardType="default"
placeholder="AAAA-MM-DD"
defaultValue={getFormValue("fecha")}
/>
<AppPickerField
name="finca_id"
holder="Granja"
data={context.allFarms} //Seleccionar el array de granjas
pickerPlaceholder="Seleccione una granja"
value={getFormValue("finca_id")}
/>
<AppFormField
name="lote"
holder="Lote"
keyboardType="numeric"
defaultValue={getFormValue("lote")}
/>
.
.
.
<SubmitButton title="Guardar" />
</AppForm>
</ScrollView>
</View>
);
}
const styles = StyleSheet.create({
container: {
backgroundColor: "white",
flex: 1,
justifyContent: "center",
marginHorizontal: 10,
// paddingTop: 50,
},
});
AppFormField
import React from "react";
import { useFormikContext } from "formik";
import { StyleSheet, View } from "react-native";
import AppTextInput from "../AppTextInput";
import ErrorMessage from "./ErrorMessage";
function AppFormField({ placeholder, name, width, holder, ...otherProps }) {
const { setFieldTouched, handleChange, errors, touched } = useFormikContext();
return (
<View style={styles.container}>
<AppTextInput
onBlur={() => setFieldTouched(name)}
onChangeText={handleChange(name)}
width={width}
holder={holder}
placeholder={placeholder}
{...otherProps}
/>
<ErrorMessage error={errors[name]} visible={touched[name]} />
</View>
);
}
const styles = StyleSheet.create({
container: {
marginBottom: 20,
marginHorizontal: 20,
},
});
export default AppFormField;
AppTextInput
import React from "react";
import { StyleSheet, View, TextInput, Text, Keyboard } from "react-native";
function AppTextInput({ placeholder = " ", holder, ...otherProps }) {
return (
<View style={styles.container}>
<Text style={styles.holder}>{holder}</Text>
<TextInput
style={styles.input}
placeholder={placeholder}
returnKeyLabel="Listo"
returnKeyType="done"
onSubmitEditing={Keyboard.dismiss}
{...otherProps}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
backgroundColor: "transparent",
},
holder: {
fontSize: 20,
textAlign: "left",
color: "#000",
opacity: 0.6,
width: "100%",
height: 30,
},
input: {
fontSize: 20,
borderBottomWidth: 1,
borderColor: "#D9D5DC",
width: "100%",
},
});
export default AppTextInput;
SOLVED:
For some reason my ScrollView component had the property paddingBottom set to 500, and just by removing it, I solved the issue.
I am making a react native app and for some reason when I tap on the text input to type something it disappears under the keyboard. I want it to come to the top of the keyboard like the way Instagram messenger and other messenger apps do it. I tried using keyboardAvoidView and setting the behavior to padding and height but none of it worked.
import {
View,
Text,
StyleSheet,
SafeAreaView,
TextInput,
TouchableOpacity,
} from "react-native";
import CommunityPost from "../components/CommunityPost";
import { Context as CommunityContext } from "../context/CommunityContext";
const Key = ({ navigation }) => {
const { createCommunityPost, errorMessage } = useContext(CommunityContext);
const [body, setBody] = useState("");
return (
<View style={styles.container}>
<SafeAreaView />
<CommunityPost />
<View style={styles.inputContainer}>
<TextInput
style={styles.input}
multiline={true}
placeholder="Type..."
placeholderTextColor="#CACACA"
value={body}
onChangeText={setBody}
/>
<TouchableOpacity
style={{ justifyContent: "center", flex: 1, flexDirection: "row" }}
onPress={() => createCommunityPost({ body })}
>
<Text style={styles.sendText}>Send</Text>
</TouchableOpacity>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "flex-start",
backgroundColor: "#2B3654",
justifyContent: "flex-end",
},
inputContainer: {
justifyContent: "flex-end",
flexDirection: "row",
},
sendText: {
color: "white",
fontSize: 25,
},
input: {
fontSize: 25,
color: "white",
borderColor: "#2882D8",
borderWidth: 1,
borderRadius: 15,
width: "80%",
marginBottom: 30,
marginLeft: 10,
padding: 10,
},
});
export default Key;
You must KeyboardAvoidingView component provided by react native.
<KeyboardAvoidingView
behavior={Platform.OS == "ios" ? "padding" : "height"}
style={styles.container}
>
<SafeAreaView />
<CommunityPost />
<View style={styles.inputContainer}>
<TextInput
style={styles.input}
multiline={true}
placeholder="Type..."
placeholderTextColor="#CACACA"
value={body}
onChangeText={setBody}
/>
<TouchableOpacity
style={{ justifyContent: "center", flex: 1, flexDirection: "row" }}
onPress={() => createCommunityPost({ body })}
>
<Text style={styles.sendText}>Send</Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
For these situations we can use one of these methods:
1.wrapping Component with <ScrollView></ScrollView>
2.wrapping Component with <KeyboardAvoidingView></KeyboardAvoidingView>
Sometimes our wrong given styles can make these happens too such as : Having a fixed value for our styles, check your margins and use one of the given methods
I hope it helps
Try using keyboardVerticalOffset and test it with different values.
For more info check this out
For those who want to keep the code clean, just use the FlatList component and add a View component involving the component with the states: {flex: 1, height: Dimensions.get ("window"). Height}.
Below left a component ready for anyone who wants to use, just wrap your component in this way:
<FormLayout>
{... your component}
</FormLayout>
Here is the solver component:
import React from 'react'
import { View, StyleSheet, FlatList, Dimensions } from 'react-native'
import Background from './Background'
const FormLayout = ({ children }) => {
const renderContent = <View style={styles.container}>
{children}
</View>
return <FlatList
ListHeaderComponent={renderContent}
showsVerticalScrollIndicator={false}
/>
}
const styles = StyleSheet.create({
container: {
flex: 1,
height: Dimensions.get('window').height * 0.95
}
})
export default FormLayout