I am trying to populate a FlatList row with the value coming from a TextInput.
Below you can find my current code.
import React, { Component } from 'react'
import { View, Text, TouchableOpacity, TextInput, StyleSheet,
StatusBar, FlatList } from 'react-native'
globalText = require('../styles/Texts.js');
globalColors = require('../styles/Colors.js');
class SearchInput extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
ingredients: ''
}
}
_handleIngredients = (text) => {
this.setState({ ingredients: text })
}
render(){
return (
<View style={styles.container}>
<StatusBar barStyle="dark-content"/>
<View>
<TextInput style={[globalText.btnFlatPrimary, styles.inputText]}
underlineColorAndroid='transparent'
placeholder='Add ingredients'
placeholderTextColor={globalColors.lightGrey}
autoCapitalize='sentences'
autoCorrect={false}
autoFocus={true}
onChangeText={this._handleIngredients}
keyboardShouldPersistTaps='handled'
/>
</View>
<FlatList
data={this.state.data}
renderItem={({text}) => (
<View style={styles.cell}>
<Text style={globalText.btnFlatPrimary}>{this.state.ingredients}</Text>
</View>
)}
/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
paddingTop: 20,
backgroundColor: globalColors.white,
},
inputText: {
paddingLeft: 16,
paddingRight: 16,
height: 60
},
cell: {
height: 60,
paddingLeft: 16,
justifyContent: 'center',
}
});
export default SearchInput;
I am probably missing something but if I pre populate the data and the ingredients states, then FlatList display correctly with the entered values. What I'd like it to populate the Flalist with the TextInput
data: [{key:'a'}],
ingredients: 'tomato'
Flatlist will only re-render if the data property changes. If you want it to re-render based on other values, you would need to pass an extraData prop.
<FlatList
data={this.state.data}
extraData={this.state.ingredients} //here
renderItem={({text}) => (
<View style={styles.cell}>
<Text style={globalText.btnFlatPrimary}>{this.state.ingredients}</Text>
</View>
)}
/>
Read more here: https://facebook.github.io/react-native/docs/flatlist.html#extradata
change: onChangeText={this._handleIngredients}
to: onChangeText={(text) => this._handleIngredients(text)}
This is for preserving the scope of this.
Related
import React, { Component } from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
class App extends Component {
constructor(props){
super(props)
this.state={
selected:null
}
}
handle=()=>{
this.setState({selected:1})
}
render() {
return (
<View>
<TouchableOpacity style={[styles.Btn, {backgroundColor:this.state.selected===1?"green":"white"}]} onPress={this.handle}>
<Text style={styles.BtnText}>Button 1</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.Btn} onPress={this.handle}>
<Text style={styles.BtnText}>Button 2</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.Btn} onPress={this.handle}>
<Text style={styles.BtnText}>Button 3</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
Btn: {
borderWidth: 1,
width: 100,
height: 20,
borderRadius: 8,
margin: 5,
padding: 10,
justifyContent: 'center',
flexDirection: 'row',
alignItems: 'center',
},
BtnText: {
fontSize: 15,
},
});
export default App;
Snack Link : https://snack.expo.dev/U_fX-6Tao-
I want to make it so when I click a button, the active button backgroundColor should change to "green" and text to "white" and the rest of the buttons backgroundColor and textColor should stay "red". But when I click another button then that button should become active and the previous active button should get back to its normal state.
It would be wonderful if you could also explain the logic behind it as I'm a newbie in React Native.
Thank you.
You are always setting the active button to the first one. Also, I would use an array to render the buttons. I would do something like this:
class App extends Component {
constructor(props){
super(props)
this.state = {
selected: null
}
}
handlePress = (item) => {
this.setState({ selected: item })
}
render() {
return (
<View>
{[...Array(3).keys()].map((item) => {
return (
<TouchableOpacity key={item} style={[styles.Btn, {backgroundColor: this.state.selected === item ? "green" : "white" }]} onPress={() => this.handlePress(item)}>
<Text style={styles.BtnText}>Button {item + 1}</Text>
</TouchableOpacity>
)
})}
</View>
);
}
}
I created an Themed component(OK I did not create it. It is there when I create the app with Expo).
import { useState } from 'react';
import { TouchableOpacity as DefaultTouchableOpacity } from 'react-native';
export type TouchableProps = DefaultTouchableOpacity['props'] & { activeBgColor?: string };
export function TouchableOpacity(props: TouchableProps) {
const [active, setActive] = useState(false);
const { style, activeBgColor, ...otherProps } = props;
if (activeBgColor) {
return (
<DefaultTouchableOpacity
style={[style, active ? { backgroundColor: activeBgColor } : {}]}
activeOpacity={0.8}
onPressIn={() => setActive(true)}
onPressOut={() => setActive(false)}
{...otherProps}
/>
);
}
return <DefaultTouchableOpacity style={style} activeOpacity={0.8} {...otherProps} />;
}
Then I use this TouchableOpacity everywhere.
<TouchableOpacity
style={tw`rounded-sm h-10 px-2 justify-center items-center w-1/5 bg-sky-400`}
activeBgColor={tw.color('bg-sky-600')}
>
<Text style={tw`text-white font-bold`}>a Button</Text>
</TouchableOpacity>
Oh I am writing TailwindCSS with twrnc by the way. You will love it.
See the screenshot below.
I've had a problem when i used useState(). i have to filter by searched words on my data and list.
i need to define my data list with State (i'd list with searched words) but when i use State, i've taken 'Invalid Hook' error.
let [list, setList] = useState(data);
//called
data={list}
I don't find where i use that , I couldn't fix for 3 days, i can't reach next step :( I hope i'll fix with expert helps...
import React, {Component, useState} from 'react'
import {
Text,
StyleSheet,
View,
FlatList,
SafeAreaView,
ScrollView,
Image,
TextInput,
} from 'react-native'
import data from '../../data'
export default class Flatlistexample extends Component {
render () {
//defined below
let [list, setList] = useState(data);
seachFilter=(text)=>{
const newData = data.filter(item=>{
const listitem= `${item.name.toLowerCase()} ${item.company.toLowerCase()}`;
return listitem.indexOf(text.toLowerCase())
})
};
return (
<SafeAreaView
style={{
flex: 1,
}}>
<FlatList
//called
data={list}
renderItem={({item, index})=>{
return (
<ScrollView>
<SafeAreaView
style={[
styles.container,
{backgroundColor: index % 2 === 0 ? '#fafafa' : '#bbb'},
]}>
<Image style={styles.profile} source={{uri: item.picture}} />
<View style={styles.rightside}>
<Text style={styles.name}>{item.name}</Text>
<Text style={styles.company}>{item.company}</Text>
</View>
</SafeAreaView>
</ScrollView>
)
}}
keyExtractor={item => item._id}
ListHeaderComponent={() => {
const [search, setSearch] = useState('');
return (
<View style={styles.seachContainer}>
<TextInput
style={styles.textInput}
placeholder={'Search...'}
value={search}
onChangeText={text=>{
setSearch(text)
}}
></TextInput>
</View>
)
}}
/>
</SafeAreaView>
)
}
}
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
alignItems: 'center',
borderBottomWidth: 1,
borderColor: 'gray',
},
profile: {
width: 50,
height: 50,
borderRadius: 25,
marginLeft: 10,
},
rightside: {
marginLeft: 20,
justifyContent: 'space-between',
marginVertical: 5,
},
name: {
fontSize: 22,
marginBottom: 10,
},
searchContainer: {
padding: 10,
borderWidth: 2,
borderColor: 'gray',
},
textInput: {
fontSize: 16,
backgroundColor: '#f9f9f9',
padding: 10,
},
})
Thank you
React hooks can be used with functional component only, here you are using class component
You need to understand the difference between functional component and class component first.
Here you are using class component so your state should be manageed in the following way
export default class Flatlistexample extends Component {
constructor(props)
{
this.state={list:[]}
}
}
and to update list
this.setState({list: <array of data>})
If you want to use hooks, your component needs to be changed something like the following:
const Flatlistexample = () => {
//defined below
let [list, setList] = useState(data);
seachFilter = (text) => {
const newData = data.filter(item => {
const listitem = `${item.name.toLowerCase()} ${item.company.toLowerCase()}`;
return listitem.indexOf(text.toLowerCase())
})
};
return (
<SafeAreaView
style={{
flex: 1,
}}>
<FlatList data={list} renderItem={Your flatlist Item}/>
</SafeAreaView>
)
}
export default Flatlistexample
Here you go, I've added lots of comments. I hope you find this instructive. Let me know if you have questions!
import React, { useMemo, useState } from 'react'
import {
Text,
StyleSheet,
View,
FlatList,
SafeAreaView,
ScrollView,
Image,
TextInput,
} from 'react-native'
import data from '../../data'
// changed this to a functional component so you can use hooks. You can't use hooks in class components.
const Flatlistexample = () => {
// you don't actually need to `useState` for your list, since you're always just filtering `data`
// you would need to use `useState` if you were receiving data from an API request, but here it's static
const [search, setSearch] = useState('') // this should live in the main component so you can filter the list
const parsedSearch = search.toLowerCase() // do this once outside the filter, otherwise you're converting it for each item in the data array
const filteredList = useMemo(
() =>
data.filter(item => {
const itemText = `${item.name.toLowerCase()} ${item.company.toLowerCase()}`
return itemText.indexOf(parsedSearch) > -1 // returns `true` if search is found in string
}),
[parsedSearch], // this will only run if parsedSearch changes
)
return (
<SafeAreaView style={{ flex: 1 }}>
<FlatList
//called
data={filteredList} // use the filtered list here
renderItem={({ item, index }) => {
return (
<ScrollView>
<SafeAreaView
style={[
styles.container,
{ backgroundColor: index % 2 === 0 ? '#fafafa' : '#bbb' },
]}
>
<Image style={styles.profile} source={{ uri: item.picture }} />
<View style={styles.rightside}>
<Text style={styles.name}>{item.name}</Text>
<Text style={styles.company}>{item.company}</Text>
</View>
</SafeAreaView>
</ScrollView>
)
}}
keyExtractor={item => item._id}
ListHeaderComponent={() => {
return (
<View style={styles.seachContainer}>
<TextInput
style={styles.textInput}
placeholder={'Search...'}
value={search}
onChangeText={text => {
setSearch(text)
}}
/>
</View>
)
}}
/>
</SafeAreaView>
)
}
export default Flatlistexample
How to get value of text in state.when i clicked on TouchableOpacity in react-native ?
I have gender value in text of TouchableOpacity . so I want to get value of selected gender in state when i clicked on TouchableOpacity.
So please help me how i can achieve this functionality.Thank you in advanced.
This is some part of my screen you can see below.
Create function like this
setGender=(props)={
this.setState({gender:props})
}
call this function from button onPress like this
onPress={()=>this.setGender("Male")}
onPress={()=>this.setGender("Female")
and show state value in Text
Example Codebase :
import React, { Component } from "react";
import {
View,
Text,
StyleSheet,
TextInput,
TouchableOpacity
} from "react-native";
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
gender: "",
textGender:"Male"
};
}
//Get text value
getTextValue = () => {
alert(this.state.gender);
console.log("Selected Gender is ", this.state.gender);
console.log("Selected Gender From Text ", this.state.textGender);
};
render() {
return (
<View style={styles.container}>
<TextInput
value={this.state.gender}
keyboardType="default"
onChangeText={gender => this.setState({ gender })}
/>
<Text>{this.state.textGender}</Text>
<TouchableOpacity
onPress={() => this.getTextValue()}
></TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
}
});
hope this will help you
onPress = (Male) => {
this.setState({ gender: 'Male'})
}
onPress1 = (Female) => {
this.setState({ gender: 'Female'})
}
<TouchableOpacity
style={styles.button}
onPress={this.onPress(Male)}
>
<Text> Male </Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={this.onPress1(Female)}
>
<Text> Female </Text>
</TouchableOpacity>*
Hope this will help you
import React, { Component } from 'react';
import { View, Text, StyleSheet, Button } from 'react-native';
export default class Home extends Component {
state = {
value: '',
};
onChangeValue = value => {
if (value !== this.state.value) {
this.setState({
value: value,
});
}
};
render() {
return (
<View style={styles.container}>
{this.state.value.length > 0 ? (
<Text
style={{
fontSize: 40,
alignSelf: 'center',
justifyContent: 'center',
}}>
{this.state.value}
</Text>
) : (
<Text
style={{
fontSize: 40,
alignSelf: 'center',
justifyContent: 'center',
}}>
I identify as you
</Text>
)}
<Button
color="#000"
title="Male"
onPress={() => this.onChangeValue('male')}
/>
<Button title="Female" onPress={() => this.onChangeValue('female')} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignContent: 'center',
justifyContent: 'center',
},
});
Feel free for doudts.
Please, look at the debugger and the screen for what could be a problem. However, the code is highly displayed below for your perusal.
More also, I aimed at navigating to another page based on the id of the selected content.
App.js
The App.js is where I defined my stackNavigator
import React, {Component} from 'react';
import { StyleSheet, Text, View} from 'react-native';
import Post from './components/Post';
import PostSingle from './components/PostSingle';
import { createStackNavigator, createAppContainer } from 'react-navigation';
const RootStack = createStackNavigator(
{
PostScreen: { screen: Post},
PostSingleScreen:{screen: PostSingle},
},
{
initialRouteName: "PostScreen"
}
);
const AppNavigator = createAppContainer(RootStack);
export default class App extends Component {
constructor(props) {
super(props);
};
render() {
return (
<View style={styles.container}>
<AppNavigator/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#F3F3F3',
}
});
Post.js
I have tried to delete alignItem = center. In fact I deleted my style to see if there is any blocking the screen from coming up.
import React, { Component } from 'react';
import {
ScrollView,
StyleSheet,
View,
Text,
InputText,
TouchableOpacity
} from 'react-native';
import axios from 'axios';
export default class Post extends Component{
constructor(props){
super(props);
this.state = {
posts: []
}
}
readMore = () => {
()=> this.props.navigation.navigate('PostSingleScreen');
debugger;
}
componentDidMount(){
axios.get(`http://localhost/rest_api_myblog/api/post/read.php`)
//.then(json => console.log(json.data.data[0].id))
.then(json => json.data.data.map(mydata =>(
{
title: mydata.title,
body: mydata.body,
author: mydata.author,
category_name: mydata.category_name,
id: mydata.id
}
)))
//.then(newData => console.log(newData))
.then(newData => this.setState({posts: newData}))
.catch(error => alert(error))
}
render(){
return (
<View>
<ScrollView style={styles.scrollContent}>
<View style={styles.header}>
<Text style={styles.headerText}>Gist Monger</Text>
</View>
{
this.state.posts.map((post, index) =>(
<View key={index} style={styles.container}>
<Text style={styles.display}>
Author: {post.author}
</Text>
<Text style={styles.display}>
Category: {post.category_name}
</Text>
<Text style={styles.display}>
Title: {post.title}
</Text>
<Text style={{overflow:'hidden'}}>
Id: {post.id}
</Text>
<TouchableOpacity style={styles.buttonContainer}
onPress = {() => this.readMore()}
>
<Text style={styles.buttonText}>
Read More
</Text>
</TouchableOpacity>
</View>
))
}
</ScrollView>
<View style={styles.footer}></View>
</View>
);
}
}
const styles = StyleSheet.create({
header: {
flex: 1,
height:40,
marginTop:50,
marginBottom:10,
flexDirection: 'row',
justifyContent:'center',
},
display: {
margin: 3,
fontSize: 16
},
headerText: {
fontWeight: 'bold',
fontSize: 40,
color: '#6200EE'
},
container: {
backgroundColor:'#efefef',
padding: 20,
margin: 5,
borderRadius:20,
justifyContent: 'center',
alignItems: 'center'
},
footer: {
flex: 1,
backgroundColor:'#000',
marginBottom:50
},
buttonContainer:{
height: 30,
width: 200,
marginTop: 15,
justifyContent: 'center',
alignItems: 'center',
borderRadius: 15,
backgroundColor:'#6200EE'
},
buttonText: {
alignContent: 'center',
color: 'white'
}
});
PostSingle.js
import React, { Component } from 'react';
import {
StyleSheet,
View,
Text
} from 'react-native';
import axios from 'axios';
export default class Post extends Component{
constructor(props){
super(props);
}
render(){
return (
<View>
<Text>My text</Text>
</View>
);
}
}
const styles = StyleSheet.create({
});
I did not test this code, but try to add flex: 1 to your container style. the main containers/components don't stretch if you don't tell them to
const styles = StyleSheet.create({
container: {
backgroundColor: '#F3F3F3',
flex: 1,
}
});
also, to check if the components render (helps debugging where the problem is), write a console log in every component's componentDidMount. if they mount, but nothing is visible, it's most likely a CSS issue. If it wasn't, it would throw errors instead of blank screen
second issue is, when you navigate you need to have params with react-navigation. the syntax for it is like this:
this.props.navigation.navigate('PostSingleScreen', { params })
so, if you have { id: someId } in your params, in the component you navigated to you will have {this.props.navigation.state.params.id}. so basically those params are inside navigation.state.params where you navigate
Let me help you with your second question. First, it is easier as said by just specifying params in your navigation.
For instance,
readMore = (id) => {
this.props.navigation.navigate('PostSingleScreen', {id:id})
}
However, in your TouchableOpacity, onPress method i.e. onPress = {() => this.readMore(post.id)}
In your PostSingle.js
import React, { Component } from 'react';
import {
StyleSheet,
View,
Text,
Button
} from 'react-native';
import axios from 'axios';
class PostSingle extends Component{
constructor(props){
super(props);
this.state = {
posts: []
}
}
componentDidMount() {
const id = this.props.navigation.state.params.id;
axios.get(`http://localhost/rest_api_myblog/api/post/read_single.php?id=${id}`)
.then(json => json.data)
.then(newData => this.setState({posts: newData}))
.catch(error => alert(error))
}
render(){
return (
<View style={styles.container}>
<Text style={styles.display}>
{this.state.posts.title}
</Text>
<Text style={styles.display}>
{this.state.posts.author}
</Text>
<Text style={styles.display}>
{this.state.posts.category_name}
</Text>
<Text style={styles.display}>
{this.state.posts.body}
</Text>
</View>
);
}
}
I hope it helps
i would suggest using flaltist for this, and not this.state.map. this should give you the same outcome
readMore(id){
//do whatever you want with the id
this.props.navigation.navigate('PostSingleScreen',{id:id}); //or pass it as a prop
debugger;
}
renderItem = ({ item, index }) => {
return (
<View key={index} style={styles.container}>
<Text style={styles.display}>
Author: {item.author}
</Text>
<Text style={styles.display}>
Category: {item.category_name}
</Text>
<Text style={styles.display}>
Title: {item.title}
</Text>
<Text style={{overflow:'hidden'}}>
Id: {item.id}
</Text>
<TouchableOpacity style={styles.buttonContainer}
onPress = {() => this.readMore(item.id)}
>
<Text style={styles.buttonText}>
Read More
</Text>
</TouchableOpacity>
</View>
);
};
render(){
return (
<View style={{flex:1}}>
<FlatList
style={{flex:1}}
data={this.state.posts}
renderItem={this.renderItem}
numColumns={1}
keyExtractor={(item, index) => item.id} //this needs to be a unique id
ListHeaderComponent = {
<View style={styles.header}>
<Text style={styles.headerText}>Gist Monger</Text>
</View>}
/>
<View style={styles.footer}/>
</View>
);
}
If you are using react-navigation 5.x then it might be possible that you are adding CSS
alignItems: "center"
to your root file i.e. App.js or index.js I just removed it and it starts working for me.
import React from 'react';
import {SafeAreaView, KeyboardAvoidingView, FlatList, View, Text, TextInput, Button, StyleSheet } from 'react-native';
export default class Guest extends React.Component {
state={
command: '',
}
constructor(props) {
super(props)
this.onChangeText = this.onChangeText.bind(this)
this.onKeyPress = this.onKeyPress.bind(this)
this.onSubmit = this.onSubmit.bind(this)
}
onChangeText(text){
const command = text.replace('\n', '');
this.setState({
command: command
})
}
onKeyPress(e){
}
onSubmit(){
}
render() {
return(
<SafeAreaView style={styles.safeAreaView}>
<KeyboardAvoidingView style={styles.keyboardAvoidingView} keyboardVerticalOffset={88} behavior="padding" enabled>
<FlatList
inverted={true}
keyboardShouldPersistTaps='always'
keyboardDismissMode='interactive'
ref='list'
style={styles.flatList}
data={[1, 2, 3]}
renderItem={(props) => {
return(<View><Text>{props.item}</Text></View>)
}}
/>
<TextInput
command={this.state.command}
onChangeText={this.onChangeText}
onKeyPress={this.onKeyPress}
onSubmit={this.onSubmit}
style={styles.textInput}
/>
</KeyboardAvoidingView>
</SafeAreaView>
)
}
}
const styles = StyleSheet.create({
safeAreaView:{
backgroundColor:"#ffffff",
},
keyboardAvoidingView:{
},
flatList:{
backgroundColor: 'red',
},
textInput:{
backgroundColor: 'yellow'
}
})
I'd like the red flatList to fill the screen (but keep height of yellow textbox).
I've tried flex:1 on flatList, but it simply makes it disappear.
FlatList inherits ScrollView's props, so solution for ScrollView will work:
<FlatList
contentContainerStyle={{ flexGrow: 1 }}
{...otherProps}
/>
Here is the original Github issue for above solution.
EDIT: The parental Views of FlatList should have flex: 1 in their style.
safeAreaView:{
backgroundColor:"#ffffff",
flex: 1
},
keyboardAvoidingView:{
flex: 1
},
use the property style wit flex:
render() {
return (
<View style={{ flex: 1 }}>
<FlatList
keyExtractor = { this.keyExtractor }
data = { this.getPOs() }
ListEmptyComponent = { this.renderEmpty }
ItemSeparatorComponent = { Separator }
renderItem = { this.renderItem }
/>
</View>
)
}
No need to add a parental view to the list, simply:
render() {
return <FlatList style={{width: '100%', height: '100%'}}
{...others}
/>;
}
you can also add height in flatList style or put flatlist inside a view and then add flex for view
In my case the problem was with virtual keyboard. when I open another page. then the keyboard suddenly dismiss. and it cause part of the page to be like someone cut it or clean it. so the solution is to before push the page that contain flatlist first dismiss the keyboard and then navigate to new page
I try every response on this issue but none of them work.
What I do was add a Parent to the FlatList and then give it a style :
<View style={{ height: SCREEN_HEIGHT}}>
SCREEN_HEIGHT is from Dimensions.get('window')
you have to import from "react-native" like this:
import { Dimensions } from "react-native"
Full example:
<View style={{ height: SCREEN_HEIGHT}}>
<FlatList
contentContainerStyle={{ flexGrow: 1 }}
keyExtractor={item => item.name}
numColumns={1}
data={this.state.dataList}
renderItem={({ item, index }) =>
this._renderItemListValues(item, index)
}
/>
</View>