Floating AutoComplete in React Native - reactjs

I am looking for an autocomplete-text-input with the floating suggestion box.
Please suggest me any package name that can help to make the same component.
I tried to many packages but nothing helps, some are pushing the next fields, others do not support click away listener.

Answer: I Suggest One Solution:
Step 1:
npm install react-native-autocomplete-input --save
Step 2:
import React, {useState, useEffect} from 'react';
// Import all the components we are going to use
import {
SafeAreaView,
StyleSheet,
Text,
TouchableOpacity,
View,
} from 'react-native';
// Import Autocomplete component
import Autocomplete from 'react-native-autocomplete-input';
const App = () => {
// For Main Data
const [films, setFilms] = useState([]);
// For Filtered Data
const [filteredFilms, setFilteredFilms] = useState([]);
// For Selected Data
const [selectedValue, setSelectedValue] = useState({});
useEffect(() => {
fetch('https://aboutreact.herokuapp.com/getpost.php?offset=1')
.then((res) => res.json())
.then((json) => {
const {results: films} = json;
setFilms(films);
//setting the data in the films state
})
.catch((e) => {
alert(e);
});
}, []);
const findFilm = (query) => {
// Method called every time when we change the value of the input
if (query) {
// Making a case insensitive regular expression
const regex = new RegExp(`${query.trim()}`, 'i');
// Setting the filtered film array according the query
setFilteredFilms(
films.filter((film) => film.title.search(regex) >= 0)
);
} else {
// If the query is null then return blank
setFilteredFilms([]);
}
};
return (
<SafeAreaView style={{flex: 1}}>
<View style={styles.container}>
<Autocomplete
autoCapitalize="none"
autoCorrect={false}
containerStyle={styles.autocompleteContainer}
// Data to show in suggestion
data={filteredFilms}
// Default value if you want to set something in input
defaultValue={
JSON.stringify(selectedValue) === '{}' ?
'' :
selectedValue.title
}
// Onchange of the text changing the state of the query
// Which will trigger the findFilm method
// To show the suggestions
onChangeText={(text) => findFilm(text)}
placeholder="Enter the film title"
renderItem={({item}) => (
// For the suggestion view
<TouchableOpacity
onPress={() => {
setSelectedValue(item);
setFilteredFilms([]);
}}>
<Text style={styles.itemText}>
{item.title}
</Text>
</TouchableOpacity>
)}
/>
<View style={styles.descriptionContainer}>
{films.length > 0 ? (
<>
<Text style={styles.infoText}>
Selected Data
</Text>
<Text style={styles.infoText}>
{JSON.stringify(selectedValue)}
</Text>
</>
) : (
<Text style={styles.infoText}>
Enter The Film Title
</Text>
)}
</View>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
backgroundColor: '#F5FCFF',
flex: 1,
padding: 16,
marginTop: 40,
},
autocompleteContainer: {
backgroundColor: '#ffffff',
borderWidth: 0,
},
descriptionContainer: {
flex: 1,
justifyContent: 'center',
},
itemText: {
fontSize: 15,
paddingTop: 5,
paddingBottom: 5,
margin: 2,
},
infoText: {
textAlign: 'center',
fontSize: 16,
},
});
export default App;

Related

React Native AsyncStorage : blank page error

I'm trying to save my data locally with AsyncStorage but there seems to be an issue when I use getData
const storeData = async (value: string) => {
//storing data to local storage of the device
try {
await AsyncStorage.setItem("#storage_Key", value);
} catch (e) {}
};
const getData = async () => {
try {
const value = await AsyncStorage.getItem("#storage_Key");
if (value !== null) {
// value previously stored
}
} catch (e) {}
};
...
<View>
<TextInput
editable
value={value}
/>
{storeData(value)}
{getData()}
</View>
I thought I would have my value back but I got a blank page. Any idea of how to use AsyncStorage ? I used https://react-native-async-storage.github.io/async-storage/docs/usage/ .
Instead of calling storeData function in the return, you should bind your async storage function to the textinput component. Below is an example code on how to use it.
// AsyncStorage in React Native to Store Data in Session
// https://aboutreact.com/react-native-asyncstorage/
// import React in our code
import React, { useState } from 'react';
// import all the components we are going to use
import {
SafeAreaView,
StyleSheet,
View,
TextInput,
Text,
TouchableOpacity,
} from 'react-native';
// import AsyncStorage
import AsyncStorage from '#react-native-community/async-storage';
const App = () => {
// To get the value from the TextInput
const [textInputValue, setTextInputValue] = useState('');
// To set the value on Text
const [getValue, setGetValue] = useState('');
const saveValueFunction = () => {
//function to save the value in AsyncStorage
if (textInputValue) {
//To check the input not empty
AsyncStorage.setItem('any_key_here', textInputValue);
//Setting a data to a AsyncStorage with respect to a key
setTextInputValue('');
//Resetting the TextInput
alert('Data Saved');
//alert to confirm
} else {
alert('Please fill data');
//alert for the empty InputText
}
};
const getValueFunction = () => {
//function to get the value from AsyncStorage
AsyncStorage.getItem('any_key_here').then(
(value) =>
//AsyncStorage returns a promise so adding a callback to get the value
setGetValue(value)
//Setting the value in Text
);
};
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={styles.container}>
<Text style={styles.titleText}>
AsyncStorage in React Native to Store Data in Session
</Text>
<TextInput
placeholder="Enter Some Text here"
value={textInputValue}
onChangeText={(data) => setTextInputValue(data)}
underlineColorAndroid="transparent"
style={styles.textInputStyle}
/>
<TouchableOpacity
onPress={saveValueFunction}
style={styles.buttonStyle}>
<Text style={styles.buttonTextStyle}> SAVE VALUE </Text>
</TouchableOpacity>
<TouchableOpacity onPress={getValueFunction} style={styles.buttonStyle}>
<Text style={styles.buttonTextStyle}> GET VALUE </Text>
</TouchableOpacity>
<Text style={styles.textStyle}> {getValue} </Text>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 10,
backgroundColor: 'white',
},
titleText: {
fontSize: 22,
fontWeight: 'bold',
textAlign: 'center',
paddingVertical: 20,
},
textStyle: {
padding: 10,
textAlign: 'center',
},
buttonStyle: {
fontSize: 16,
color: 'white',
backgroundColor: 'green',
padding: 5,
marginTop: 32,
minWidth: 250,
},
buttonTextStyle: {
padding: 5,
color: 'white',
textAlign: 'center',
},
textInputStyle: {
textAlign: 'center',
height: 40,
width: '100%',
borderWidth: 1,
borderColor: 'green',
},
});
export default App;

React Native key in AsyncStorage

I am new in React Native and I want to apply AsyncStorage in my project. I am doing a project where I can add Classroom in the flatlist, then in each Classroom, I can add Student names of each class using flatlist. Asyncstorage will be applied in both Classroom list and Student list.
My expectation is , I add classroom A , classroom B and classroom C , then when I pressed Clasroom A, I can add the name of students and when I go to classroom B , the name list is still empty waiting for me to fill the list.
My actual result is , after I add studentA , studentB , studentC in classroom A, when I go to classroom B, the 3 students in classroom A is still available in the list of classroom B.
So , how can I fix this to meet my requirement or it would be very helpful and much appreciated if you could provide a code with explanation. Thank you very much in advance
this is my code for the MainMenu.js where I need to add classroom :
import React, { useState , useEffect } from 'react';
import {
View,
Text,
TouchableOpacity,
FlatList,
Alert,
TextInput,
StyleSheet,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import AsyncStorage from '#react-native-async-storage/async-storage';
import { useNavigation } from '#react-navigation/native';
import { CardStyleInterpolators } from '#react-navigation/stack';
export default function MainMenu(){
const [classroomInput, setClassroomInput] = useState('');
const [classroom, setClassroom] = useState([]);
const navigation = useNavigation();
useEffect(() => {
getClassroom();
}, []);
useEffect(() => {
saveClassroom(classroom);
}, [classroom]);
const saveClassroom = async (classroom) => {
try {
const stringifyClassroom = JSON.stringify(classroom);
await AsyncStorage.setItem('classroom', stringifyClassroom);
} catch (error) {
console.log(error);
}
};
const getClassroom = async () => {
try {
const classrooms = await AsyncStorage.getItem('classroom');
if (classrooms !== null) {
setClassroom(JSON.parse(classrooms));
}
} catch (error) {
console.log(error);
}
};
const addClassroom = () => {
if (classroomInput === ''){
Alert.alert('Error', 'Please input class');
} else {
const newClassroom = {
id: Math.random().toString(),
Classroom: classroomInput,
};
setClassroom([...classroom,newClassroom]);
setClassroomInput('');
}
};
const deleteClassroom = (classroomId) => {
const newClassrooms = classroom.filter(item => item.id !== classroomId);
setClassroom(newClassrooms);
};
return (
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder={'Add Classrooms'}
value={classroomInput}
onChangeText={(text) => setClassroomInput(text)}
/>
<TouchableOpacity onPress={() => addClassroom()} style={styles.button}>
<Text>Add Classroom</Text>
</TouchableOpacity>
<FlatList
style={styles.flatlist}
data={classroom}
keyExtractor = { (item) => item.id.toString() }
renderItem={({ item }) => (
<TouchableOpacity onPress= {() => navigation.navigate('Classroom', item)} >
<View style={styles.listItem}>
<View>
<Text>
{item?.Classroom}
</Text>
</View>
<View >
<TouchableOpacity style={[styles.delete ]} onPress={() => deleteClassroom(item?.id)}>
<Icon name="remove" size={15} color={'#fff'} />
</TouchableOpacity>
</View>
</View>
</TouchableOpacity>
)}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
input: {
width: '70%',
borderBottomWidth: 1,
marginBottom: 20,
},
button: {
backgroundColor: 'lightblue',
padding: 10,
marginBottom: 10,
},
delete: {
backgroundColor: '#ff3333',
padding: 5,
color: '#fff',
borderWidth: 1,
borderColor: '#ff9999',
borderRadius: 5,
},
listItem: {
flexDirection: 'row',
justifyContent: 'space-between',
width: '70%',
alignItems: 'center',
},
});
and this is the Classroom.js where I will add the student list
import React, { useState , useEffect } from 'react';
import {
View,
Text,
TouchableOpacity,
FlatList,
Alert,
TextInput,
StyleSheet,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import AsyncStorage from '#react-native-async-storage/async-storage';
import { useRoute } from '#react-navigation/core';
const Classroom = ( {navigation}) => {
const [studentInput, setStudentInput] = useState('');
const [student, setStudent] = useState([]);
const route = useRoute();
useEffect(() => {
getStudent();
}, []);
useEffect(() => {
saveStudent(student);
}, [student]);
const saveStudent = async (student) => {
try {
const stringifyStudent = JSON.stringify(student);
await AsyncStorage.setItem('student', stringifyStudent);
} catch (error) {
console.log(error);
}
};
const getStudent = async () => {
try {
const students = await AsyncStorage.getItem('student');
if (students !== null) {
setStudent(JSON.parse(students));
}
} catch (error) {
console.log(error);
}
};
const addStudent = () => {
if (studentInput === ''){
Alert.alert('Error', 'Please input student name');
} else {
const newStudent = {
id: Math.random().toString(),
Name: studentInput,
};
setStudent([...student,newStudent]);
setStudentInput('');
}
};
const deleteStudent = (studentId) => {
const newStudent = student.filter(item => item.id !== studentId);
setStudent(newStudent);
};
return (
<View styles={styles.container}>
<TouchableOpacity onPress={()=> navigation.goBack()} style={styles.button}>
<Text>Back</Text>
</TouchableOpacity>
<Text style={{fontWeight: 'bold', fontSize: 20}}>{route.params.Classroom}</Text>
<TextInput
style={styles.input}
placeholder={'Add Student Name'}
value={studentInput}
onChangeText={(text) => setStudentInput(text)}
/>
<TouchableOpacity onPress={()=> addStudent()} style={styles.button}>
<Text>Add Student</Text>
</TouchableOpacity>
<FlatList
style={styles.flatlist}
data={student}
keyExtractor = { (item) => item.id.toString() }
renderItem={({ item }) => (
<View style={styles.listItem}>
<View>
<Text style={[styles.classText , {fontSize: 18}]}>
{item?.Name}
</Text>
</View>
<View >
<TouchableOpacity style={[styles.delete ]} onPress={() => deleteStudent(item?.id)}>
<Icon name="remove" size={15} color={'#fff'} />
</TouchableOpacity>
</View>
</View>
)}
/>
</View>
);
};
export default Classroom;
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
input: {
width: '70%',
borderBottomWidth: 1,
marginBottom: 20,
},
button: {
backgroundColor: 'lightblue',
padding: 10,
marginBottom: 10,
},
listItem: {
flexDirection: 'row',
justifyContent: 'space-between',
width: '70%',
alignItems: 'center',
},
delete: {
backgroundColor: '#ff3333',
padding: 5,
color: '#fff',
borderWidth: 1,
borderColor: '#ff9999',
borderRadius: 5,
},
});
Your problem is you are setting all the students with the same key student.
What you need to do instead is use the class name to set a dynamic key for your storage if your class names are unique otherwise you need to use something like uuid in order to create unique ids for your classes.
for example you can do this in your save student function
const saveStudent = async (student) => {
try {
const stringifyStudent = JSON.stringify(student);
await AsyncStorage.setItem(`class${class.name}:students`, stringifyStudent);
} catch (error) {
console.log(error);
}
};
and do this for your get student function
const getStudent = async () => {
try {
const students = await AsyncStorage.getItem(`class${class.name}:students`);
if (students !== null) {
setStudent(JSON.parse(students));
}
} catch (error) {
console.log(error);
}
};
Also try using uuid package instead of Math.random for your id creation. It's true that getting same numbers using Math.random is very unlikely but it is still possible but with uuid this is impossible.

React Native Hooks Search Filter FlatList

I am trying to make a Covid19 React Native Expo app. It contains a search filter from which user will select a country then the selected country results will be shown to the user. I keep getting this error on my Android device "Unexpected Identifier You" while on web pack the countries load but they don't filter correctly.
Working Snack Link: https://snack.expo.io/#moeez71/ac5758
Here is my code:
import React, { useState, useEffect } from "react";
import {
ActivityIndicator,
Alert,
FlatList,
Text,
StyleSheet,
View,
TextInput,
} from "react-native";
export default function ABCDEE() {
const [arrayholder, setArrayholder] = useState([]);
const [text, setText] = useState("");
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const fetchAPI = () => {
return fetch("https://api.covid19api.com/countries")
.then((response) => response.json())
.then((responseJson) => {
setData(responseJson);
setLoading(false);
setArrayholder(responseJson);
})
.catch((error) => {
console.error(error);
});
};
useEffect(() => {
fetchAPI();
});
const searchData = (text) => {
const newData = arrayholder.filter((item) => {
const itemData = item.Country.toUpperCase();
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
setData(newData);
setText(text);
};
const itemSeparator = () => {
return (
<View
style={{
height: 0.5,
width: "100%",
backgroundColor: "#000",
}}
/>
);
};
return (
<View>
{loading === false ? (
<View style={styles.MainContainer}>
<TextInput
style={styles.textInput}
onChangeText={(text) => searchData(text)}
value={text}
underlineColorAndroid="transparent"
placeholder="Search Here"
/>
<FlatList
data={data}
keyExtractor={(item, index) => index.toString()}
ItemSeparatorComponent={itemSeparator}
renderItem={({ item }) => (
<Text style={styles.row}>{item.Country}</Text>
)}
style={{ marginTop: 10 }}
/>
</View>
) : (
<Text>loading</Text>
)}
</View>
);
}
const styles = StyleSheet.create({
MainContainer: {
paddingTop: 50,
justifyContent: "center",
flex: 1,
margin: 5,
},
row: {
fontSize: 18,
padding: 12,
},
textInput: {
textAlign: "center",
height: 42,
borderWidth: 1,
borderColor: "#009688",
borderRadius: 8,
backgroundColor: "#FFFF",
},
});
You had made two mistakes in the above code
useEffect second parameter should be a empty array for it act as componentDidMount()
useEffect(() => {
fetchAPI();
},[])
in FlatList renderItem need to destructure the item.
renderItem={( {item} ) => <Text style={styles.row}
>{item.Country}</Text>}
Working code
import React, {useState, useEffect} from "react"
import { ActivityIndicator, Alert, FlatList, Text, StyleSheet, View, TextInput } from 'react-native';
export default function ABCDEE(){
const [arrayholder,setArrayholder] =useState([])
const[text, setText] = useState('')
const[data, setData] = useState([])
const [loading , setLoading] = useState(true)
const fetchAPI = ()=> {
return fetch('https://api.covid19api.com/countries')
.then((response) => response.json())
.then((responseJson) => {
setData(responseJson)
setLoading(false)
setArrayholder(responseJson)
}
)
.catch((error) => {
console.error(error);
});
}
useEffect(() => {
fetchAPI();
},[])
const searchData= (text)=> {
const newData = arrayholder.filter(item => {
const itemData = item.Country.toUpperCase();
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1
});
setData(newData)
setText(text)
}
const itemSeparator = () => {
return (
<View
style={{
height: .5,
width: "100%",
backgroundColor: "#000",
}}
/>
);
}
return (
<View style={{flex:1}} >
{loading === false ?
<View style={styles.MainContainer}>
<TextInput
style={styles.textInput}
onChangeText={(text) => searchData(text)}
value={text}
underlineColorAndroid='transparent'
placeholder="Search Here" />
<FlatList
data={data}
keyExtractor={ (item, index) => index.toString() }
ItemSeparatorComponent={itemSeparator}
renderItem={( {item} ) => <Text style={styles.row}
>{item.Country}</Text>}
style={{ marginTop: 10 }} />
</View>
: <Text>loading</Text>}
</View>
);
}
const styles = StyleSheet.create({
MainContainer: {
paddingTop: 50,
justifyContent: 'center',
flex: 1,
margin: 5,
},
row: {
fontSize: 18,
padding: 12
},
textInput: {
textAlign: 'center',
height: 42,
borderWidth: 1,
borderColor: '#009688',
borderRadius: 8,
backgroundColor: "#FFFF"
}
});
There are multiple issues with your implementation. I will point out some mistake/ignorance. You can clean up you code accordingly.
Do not create 2 state to keep same data. ie. arrayholder and data.
Change text value on search, don't the data. based on that text filter
Hooks always define some variable to be watched.
Update: Seems there is an issue with flex in android view, i use fixed height it is visible.
Just a hack for android issue. minHeight
MainContainer: {
paddingTop: 50,
justifyContent: 'center',
flex: 1,
margin: 5,
minHeight: 800,
},
Working link: https://snack.expo.io/kTuT3uql_
Updated code:
import React, { useState, useEffect } from 'react';
import {
ActivityIndicator,
Alert,
FlatList,
Text,
StyleSheet,
View,
TextInput,
} from 'react-native';
export default function ABCDEE() {
const [text, setText] = useState('');
const [state, setState] = useState({ data: [], loading: false }); // only one data source
const { data, loading } = state;
const fetchAPI = () => {
//setState({data:[], loading: true});
return fetch('https://api.covid19api.com/countries')
.then(response => response.json())
.then(data => {
console.log(data);
setState({ data, loading: false }); // set only data
})
.catch(error => {
console.error(error);
});
};
useEffect(() => {
fetchAPI();
}, []); // use `[]` to avoid multiple side effect
const filterdData = text // based on text, filter data and use filtered data
? data.filter(item => {
const itemData = item.Country.toUpperCase();
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
})
: data; // on on text, u can return all data
console.log(data);
const itemSeparator = () => {
return (
<View
style={{
height: 0.5,
width: '100%',
backgroundColor: '#000',
}}
/>
);
};
return (
<View>
{loading === false ? (
<View style={styles.MainContainer}>
<TextInput
style={styles.textInput}
onChangeText={text => setText(text)}
value={text}
underlineColorAndroid="transparent"
placeholder="Search Here"
/>
<FlatList
data={filterdData}
keyExtractor={(item, index) => index.toString()}
ItemSeparatorComponent={itemSeparator}
renderItem={({ item }) => (
<Text style={styles.row}>{item.Country}</Text>
)}
style={{ marginTop: 10 }}
/>
</View>
) : (
<Text>loading</Text>
)}
</View>
);
}
const styles = StyleSheet.create({
MainContainer: {
paddingTop: 50,
justifyContent: 'center',
//flex: 1,
margin: 5,
height: 800,
},
row: {
fontSize: 18,
padding: 12,
},
textInput: {
textAlign: 'center',
height: 42,
borderWidth: 1,
borderColor: '#009688',
borderRadius: 8,
backgroundColor: '#333',
},
});
It seems like the error comes from the catch block when you fetch your data. The response comes with a 200 status, so it's not an issue with the endpoint itself. I console.logged the response and it seems fine. The problem is when you parse the response and try to use it in the second then() block, so the catch block fires up. I could not debug it right in the editor you use, but I would check what type of object I'm receiving from the API call.
This is not a direct answer to your question but I didn't want this to get lost in the comments as it is directly related with your efforts on this app.
App Store and Google Play Store no longer accept apps that have references to Covid-19 https://developer.apple.com/news/?id=03142020a
You can only publish apps about Covid-19 if you are reputable source like a government's health department.
Therefore, I urge you to reevaluate your efforts on this app.

I keep getting this error. TypeError: addItems is not a function. (In 'addItems(text)', 'addItems' is an instance of Object)

This is the error I get every time I try and add something to my list.
TypeError: addItems is not a function. (In 'addItems(text)', 'addItems' is an instance of Object)
I cannot figure out what I am doing wrong. Im new to react-native so any help would be greatly appreciated.
Here is my App.js
import React, { useState } from 'react';
import { View, Text, StyleSheet, ImageBackground, FlatList } from 'react-native';
import 'react-native-get-random-values';
import { v4 as uuidv4 } from 'uuid';
import { uuid } from 'uuidv4';
import Header from './Componets/Header';
import AddItem from './Componets/AddItem';
import background from './Images/sunrise-in-the-smoky-mountains.jpg';
import ListItem from './Componets/ListItem';
const App = () => {
const [item, setItems] = useState([
// {
// id: uuidv4(),
// name: ''
// },
{
id: uuidv4(),
name: "gym"
},
{
id: uuidv4(),
name: "study"
}
]);
const addItems = (text) => {
setItems(prevItems => {
return [{ id: uuidv4(), text }, ...prevItems]
})
}
const deleteItem = (id) => {
setItems(prevVal => {
return prevVal.filter(item => item.id != id)
})
}
return (
<View style={styles.container}>
<ImageBackground source={background} style={styles.image}>
<Header
title="Gotta get this done!" />
<AddItem
addItem={addItems}
/>
<FlatList
data={item}
renderItem={({ item }) => (
<ListItem item={item.name} deleteItem={deleteItem} />
)}
/>
</ImageBackground>
</View>
)
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
image: {
flex: 1,
resizeMode: "cover",
justifyContent: "center"
}
})
export default App;
Here is where I call the function and get the error.
import React, { useState } from 'react';
import { View, Text, StyleSheet, TextInput, TouchableOpacity, Button } from 'react-native';
const AddItem = ( addItems ) => {
const [text, setText] = useState("");
const onChange = (inputVal) => setText(inputVal);
return (
<View style={styles.addItemView}>
<TextInput
style={styles.inputText}
placeholder="Add item to list..."
onChangeText={onChange}
/>
<TouchableOpacity style={styles.button}>
<Button title="Add Item" onPress={() => addItems(text)} />
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
addItemView: {
flex: 1,
flexDirection: "row",
alignItems: 'center'
},
inputText: {
fontSize: 20,
backgroundColor: "white",
alignItems: 'center',
justifyContent: 'center',
borderWidth: 1,
width: 250,
},
button: {
alignItems: "center",
justifyContent: "center",
height: 40,
backgroundColor: "#bbc7ad",
borderRadius: 10,
borderWidth: 2,
borderColor: "#99a191",
marginLeft: 20,
}
})
export default AddItem;
You are passing addItems function as a prop in
<AddItem
addItem={addItems}
/>
When you pass any function or value to any functional component in React you can access them only via props so to access addItems you need to access this function from the props
You can do that by following ways
Method 1
const AddItem = ( props ) => {
// We are extracting addItem function from props
const {addItem} = props
const [text, setText] = useState("");
const onChange = (inputVal) => setText(inputVal);
return (
<View style={styles.addItemView}>
<TextInput
style={styles.inputText}
placeholder="Add item to list..."
onChangeText={onChange}
/>
<TouchableOpacity style={styles.button}>
<Button title="Add Item" onPress={() => addItem(text)} />
</TouchableOpacity>
</View>
);
};
Method 2 :
const AddItem = ({addItem} ) => {
.....
return (
<View style={styles.addItemView}>
......
<TouchableOpacity style={styles.button}>
<Button title="Add Item" onPress={() => addItem(text)} />
</TouchableOpacity>
</View>
);
};
This seems to work for now. Still unclear as to why using destructuring in my original version didnt work. Please chime in if you can help with that. Thanks!
const AddItem = (props) => {
const [text, setText] = useState("");
const onChange = inputVal => setText(inputVal);
return (
<View style={styles.addItemView}>
<TextInput
style={styles.inputText}
placeholder="Add item to list..."
onChangeText={onChange}
/>
<TouchableOpacity style={styles.button}>
<Button title="Add Item" onPress={() => props.addItem(text)} />
</TouchableOpacity>
</View>
);
};

unexpected token when trying to declare a variable inside flatlist in react native

i'm trying to declare an variable inside the FlatList component in React Native
But i get unexpected token, when i do declare it.
const FixturesScreen = ({ navigation }) => (
<ScrollView style={styles.container}>
<FlatList
data={clubData.data.clubs}
renderItem={({ item }) => (
let fixture = item.name //unexpected token
<View>
<View>
<Text style={styles.itemTitle}>{item.name}</Text>
<ScrollView horizontal>
<Text style={styles.listItem}>{fixture}</Text>
</ScrollView>
</View>
</View>
)
}
/>
</ScrollView>
)
here is my full FixturesScreen cdoe
import React from 'react'
import { View, Text, FlatList, ScrollView, StyleSheet } from 'react-native'
import Ionicons from 'react-native-vector-icons/Ionicons'
import clubData from '../../clubData'
const styles = StyleSheet.create({
container: {
backgroundColor: '#4BABF4',
},
itemTitle: {
color: 'black',
fontSize: 20,
marginTop: 20,
marginBottom: 10,
marginLeft: 15,
},
listItem: {
color: '#FFFFFF',
fontSize: 18,
textAlign: 'center',
marginRight: 15,
marginLeft: 15,
backgroundColor: '#77BEF5',
width: 120,
paddingVertical: 10,
},
})
const CURRENTTGAMEWEEK = 30
const i = CURRENTTGAMEWEEK
const nxt1 = i + 1
const nxt2 = nxt1 + 2
const nxt3 = nxt2 + 1
const nxt4 = nxt3 + 1
const nxt5 = nxt4 + 1
// let fixture
// const team = clubData.data.clubs[0].name
// const hTeam = clubData.data.clubs[0].fixtures[0].homeTeam
// const hTeamShort = clubData.data.clubs[0].fixtures[0].homeTeamShort
// const aTeamShort = clubData.data.clubs[0].fixtures[0].awayTeamShort
//
// if (team === hTeam) // working
// fixture = aTeamShort
// else
// fixture = hTeamShort
console.log(`Now is playing ${fixture}`)
const FixturesScreen = ({ navigation }) => (
<ScrollView style={styles.container}>
<FlatList
data={clubData.data.clubs}
renderItem={({ item }) => (
let fixture = item.name
<View>
<View>
<Text style={styles.itemTitle}>{item.name}</Text>
<ScrollView horizontal>
<Text style={styles.listItem}>{fixture}</Text>
</ScrollView>
</View>
</View>
)
}
/>
</ScrollView>
)
FixturesScreen.navigationOptions = {
tabBarTestIDProps: {
testID: 'TEST_ID_HOME',
accessibilityLabel: 'TEST_ID_HOME_ACLBL',
},
tabBarLabel: 'Main',
tabBarIcon: ({ tintColor, focused }) => (
<Ionicons
name={focused ? 'ios-home' : 'ios-home-outline'}
size={26}
style={{ color: tintColor }}
/>
),
}
export default FixturesScreen
So basically what i'm trying to do is declare homeTeam, awayTeam and Fixture inside the flatlist, so i can do an if/else conditional rendering inside the flatlist. I can achieve that outside the flatlist component but it is not right, because i can not compare all objects at once.
While using arrow functions () => ('someValue') is a shortcut for () => { return 'someValue'}.
(param1, param2, …, paramN) => { statements }
(param1, param2, …, paramN) => expression
// equivalent to: (param1, param2, …, paramN) => { return expression; }
// Parentheses are optional when there's only one parameter name:
(singleParam) => { statements }
singleParam => { statements }
// A function with no parameters should be written with a pair of parentheses.
() => { statements }
// Parenthesize the body of function to return an object literal expression:
params => ({foo: bar})
So if you want to run some code before returning a value you should do like below;
const FixturesScreen = ({ navigation }) => (
<ScrollView style={styles.container}>
<FlatList
data={clubData.data.clubs}
renderItem={({ item }) => { //change to curly braces
let fixture = item.name;
// do something here
return (
<View>
<View>
<Text style={styles.itemTitle}>{item.name}</Text>
<ScrollView horizontal>
<Text style={styles.listItem}>{fixture}</Text>
</ScrollView>
</View>
</View>
);
}}
/>
</ScrollView>
)

Resources