How can i change the FlatList item background color when button is pressed in React Native - react-native

Let's suppose that i've a FlatList with some items, i press into one of them, then opens me another screen with the details of that item. Alright, so what i need is, after pressing the button called "Got it!" and goes into the back screen(FlatList screen), how can i set the background color to green in the row selected?
So i click in one item of the FlatList, then it shows me another screen with the details of that item
Once im in the Details screen, i press the button "Got it!", and it brings me back to the FlatList screen
This is exactly what i need, set a background color only in the View shown in that item, if i press another item and do the same thing, it will be shown changed the background both of them, and so on...
NOTE: class Details and ProfileActivity are inside App.js as a childs.
class ProfileActivity extends Component
{
GetFlatListItem (Description, Tutorial, Imagen, Title) {
Alert.alert(Description);
this.props.navigation.navigate('Fourth', {Tutorial, Imagen, Title});
}
return(
<View style = { styles.MainContainer }>
<Button title="Logout" onPress={ () => goBack(null) } />
<Text style = {styles.TextComponentStyle}> { this.props.navigation.state.params.Email } </Text>
<FlatList
data={ this.state.dataSource }
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem={({item}) => <View style={{flex: 1, flexDirection: 'row'}}> <Text style={styles.points}>+ {item.points}</Text>
<Text style={styles.flatview} onPress={this.GetFlatListItem.bind
(this, item.description, item.tutorial, item.image, item.title)} >{item.title}</Text></View>}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
class Details extends Component{
onPress = () => {
this.setState({
const {goBack} =this.props.navigation;
})
}
return(
<View style = { styles.MainContainer }>
<TouchableHighlight
style={styles.buttonStyle}
onPress={this.onPress}
>
<Text> Got it! </Text>
</TouchableHighlight>
<Text style = {styles.TextComponentStyle}> { this.props.navigation.state.params.Title } </Text>
<Image
style={{width: 66, height: 58}}
source={{uri: this.props.navigation.state.params.Imagen}}
/>
<Text style = {styles.TextComponentStyle}> { this.props.navigation.state.params.Tutorial } </Text>
</View>
);
}
export default MainProject = createStackNavigator(
{
First: { screen: App },
Second: { screen: ProfileActivity },
Fourth: { screen: Details }
});
What i think is pass some values to the method onPress() in Details class, but i don't know which one exactly and how. Can somebody help me?

You will have to create this.state.someArrayName and copy from this.props.navigation.state.params and add backgroundColor key to each object and add your color. Apply that color to your items' view background color. *{{backgroundColor : item.backgroundColor}}
Create a function changeColor to change the color of backgroundColor
In your GetFlatListItem function, pass that function to detail view
On Detail View, call that changeColor function. this.props. changeColor() when you tap Got it button.

Related

How can I link the button outside flatlit to hide and show the items inside the flatlist in each section react native

I am using flatlist in my app to show the result of the game by using API, I have a button outside the flatlist, I want the user to click the button and by clicking the button toggle switch will appear with each game and a user can switch off to hide the games and switch on to show the games.
First problem how can I link the button with the render function of flatlist to show the toggle switch.
Seconde is that how can I use the toggle switch to show and hide the games in flatlist.
<View style={{flex:1,}}>
<TouchableOpacity onPress={this.renderItem }> // What should I do here?
<Text style={{fontSize:30,color:'blue'}}>show/hide</Text>
</TouchableOpacity>
<DraggableFlatList
data={this.state.dataSource}
onDragEnd={this.dataSource}
renderItem={this.renderItem}
keyExtractor={item => item.GameId.toString()}
ItemSeparatorComponent={this.renderSeprator}
refreshing = {this.state.refreshing}
onRefresh = {this.handleRefresh}
/>
renderItem=({item,navigation,drag,btnvalue1})=>{
const current = new Date();
const currentHour = current.getHours();
return(
<ScaleDecorator>
<TouchableOpacity style={styles.item}
onLongPress={drag}
onPress={
() => this.props.navigation.navigate('ResultsStack',
{ screen: 'Result', params: { resultDate: this.state.resultDate ,GameId: item.GameId } }
//() => this.props.navigation.navigate('ResultsStack', { screen: 'Result' }
)} >
<Image style={styles.img}
source={{
uri: item.ImgUrl,
}}
/>
<Text style={styles.title}>{item.GameDescp} [{item.DrawRef}] [{item.DayName?.slice(0, 3)}]</Text>
<Text style={styles.txt3}>{item.Result03}</Text>
**//On click I want to hide this Ionicon and show a toggle switch**
<Ionicons
name="chevron-forward-outline"
style={styles.iconarrow}
//color={color}
size={30}
></Ionicons>
{this.btnvalue1 === 1 ? (
<Switch
style={styles.iconarrow}
trackColor={{ false: "#767577", true: "#81b0ff" }}
ios_backgroundColor="#3e3e3e"
/>) : null}
</TouchableOpacity>
</ScaleDecorator>

Updating button state which is clicked, inside RenderItem of Flat-list, in React Native

I am new to React Native and trying to accomplish something like below, where simple list from server is rendering in a list with a button. Button, upon click, will be disabled and opacity will be changed.
I am able to create the UI but when I click any button that says Join, previous clicked button resets it state to original. In other words, only one button displays clicked state all the time.
so my code is something like
constructor(props){
super(props);
this.state = {selectedIndices: false, groupsData: ''};
}
Flatlist inside render method looks like
<FlatList style={styles.list}
data={this.state.groupsData}
keyExtractor={(groups) => {
return groups.groupId.toString();
}}
renderItem={(item, index) => {
return this.renderGroupItem(item);
}}/>
RenderGroupItem
renderGroupItem = ({item} )=>(
<GroupItem group = {item} style={{height: '10%'}} onPress = {() => this.onJoinButtonPress(item)}
index = {this.state.selectedIndices}/>
)
onJoinButtonPress
onJoinButtonPress = (item) =>{
this.setState({selectedIndices: true});
}
GroupItem
render(){
if(this.props.group.groupId === this.props.index){
return(
<View style = {[styles.container]}>
<Image source={{uri: 'some Image Url'}} style={styles.roundImage}/>
<Text style={styles.groupText}>{this.props.group.name}</Text>
<View >
<TouchableOpacity style = {[styles.button, {opacity: 0.4}]} activeOpacity = { .5 } onPress = {this.props.onPress}
disabled = {true}>
<Text style = {{color: 'white', fontSize: 12}}>Joined</Text>
</TouchableOpacity>
</View>
</View>
);
}else{
return(
<View style = {styles.container}>
<Image source={{uri: 'Some Image Url'}} style={styles.roundImage}/>
<Text style={styles.groupText}>{this.props.group.name}</Text>
<View >
<TouchableOpacity style = {styles.button} activeOpacity = { .5 } onPress = {this.props.onPress}>
<Text style = {{color: 'white', fontSize: 12}}>Join</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
Now I know that I need to pass an array or hasmap which contains mapping of items that have been clicked but I dont know how to do that. Need desperate help here.
I was able to overcome above problem after maintaining a boolean in the groupsData. Upon selection, I update a boolean "groupsJoined" in groupsData and update the state of groupsData which will invoke render. Inside GroupsItem class, I added a check that if data from props has joinedGroups as true then render selected state else non selected state.
Courtesy https://hackernoon.com/how-to-highlight-and-multi-select-items-in-a-flatlist-component-react-native-1ca416dec4bc

Need to double press to release focus on Text Input from within a Modal with KeyboardAvoidingView

I have a Modal wrapping a KeyboardAvoidingView wrapping a few animated components. One of them is a TextInput and the other is a Button. When clicking on the button, keyboard is first hidden, and then need to click once again to reach the buttons "onPress"
Looked into the solution of wrapping the components with a scroll view and using a the prop keyboardShouldPersistTaps={'always'} but that doesn't work.
constructor(props) {
super(props);
this.paddingInput = new Animated.Value(0);
this.state = {
modalVisible: false,
otherTip: '',
}
}
renderHoveringNote = () => {
const {total, currentTipPercent} = this.props.rootStore.orderStore;
return (
<View>
<KeyboardAvoidingView style={{flex: 1}}>
<Animated.View style={{
marginBottom: this.paddingInput,
flex: 1
}}>
<View>
<Text>Enter custom amount</Text>
</View>
<TextInput
onChangeText={value => {
this.setState({otherTip: value})
}}
autoFocus
value={this.state.otherTip}
/>
<Button title='Save'
onPress={()=>{
...do some stuff here
this.setState({modalVisible: false});
Keyboard.dismiss();
}}
</Animated.View>
</KeyboardAvoidingView>
</View>
)
};
renderOtherTipModal = () => {
return (
<Modal
isVisible={this.state.modalVisible}
onBackdropPress{()=>this.setState({modalVisible:false})}
style={{margin: 0, flex: 1}}
hideModalContentWhileAnimating={true}
>
{this.renderHoveringNote()}
</Modal>
)
};
One click should reach the onPress of the button
Figured it out - I had a few Scroll Views as parents to the Modal. It is important to have ALL of the parent Scroll Views to have keyboardShouldPersistTaps={'always'}.
After adding that, it worked great.

How to identify which view is clicked programmatically

I am developing an android application on react native. Which has several buttons and I want to perform different actions on click of each button.
I am quite familiar with android sdk, in android sdk android:id attribute is present to identify components. But the problem in react native is how to identify which button is clicked by user.
<View style = { styles.button_container } >
<Text
onPress={() => } >Component
</Text>
<Text
onPress={() => } >About
</Text>
</View>
you can send a parameter with the button clicked, something like this:
function MenuComponent(props) {
return (
<View style = { styles.button_container } >
<Text
onPress={() => props.onClick('component')} >Component
</Text>
<Text
onPress={() => props.onClick('about')} >About
</Text>
</View>
)
}
Assuming you are sending an onClick prop from the parent. The the parent will know which of the children elements was clicked.
class ParentComponent extends Component {
onClickMenu = (button) => {
console.log(button);
}
render() {
return (
<View>
<MenuComponent onClick={this.onClickMenu} />
</View>
);
}
}
The onClickMenu will get the button param with the clicked button on the child component, from there you can decide what to do for each case.

How to handle a touch gesture by multiple components in react native?

Using React Native 0.47 and yarn, I'm creating an introduction section in which you can swipe through multiple pages and finally get to the home page.
So we swipe pages from right to left and move like this: Slide1 -> Slide2 -> Slide3 -> Slide4 -> Home . I have a component that displays a slide page which covers all of the screen. For example, first slide looks like this:
And the code for that is :
class IntroSlide extends Component {
render () {
return (
<View style={[styles.introSlide, this.props.myStyle]}>
<View style={styles.introSlideIconView}>
<Icon name={this.props.iconName} size={SLIDE_ICON_SIZE} color="white"/>
</View>
<View style={styles.introSlideTextView}>
<Text style={styles.introSlideTextHeader}> {this.props.headerText} </Text>
<Text style={styles.introSlideText}> {this.props.text} </Text>
</View>
</View>
);
}
}
And i use it that here:
import AppIntro from 'react-native-app-intro';
// Other imports here
export default class Intro extends Component {
render() {
return (
<View style={{flex: 1}}>
<AppIntro
showSkipButton={false}
nextBtnLabel={<Text style={styles.introButton}>بعدی</Text>}
doneBtnLabel={<Text style={styles.introButton}>شروع</Text>}
>
<IntroSlide
iconName="user"
myStyle={styles.introSlide1}
headerText="DontCare"
text= "SomeTextDoesntMatter"
/>
</AppIntro>
</View>
);
}
}
I'm using react-native-app-intro for this which provides me a very cool swiper but here's the problem:
I have a small View component with an Icon (react-native-vector-icons) in it as you can see that i want to rotate as i swipe to the next page. I created a panResponder in IntroSlide and set it to top View of it. but my slide can't receive any events. i think some parent views provided by react-native-app-intro captures all the events and i can still swipe through pages but no console log appears. here's what i did:
class IntroSlide extends Component {
constructor(props) {
super(props);
const panResponder = PanResponder.create({
onStartShouldSetPanResponder: () => true,
onPanResponderMove: () => console.log("Moving"),
});
this.pan = panResponder;
}
render () {
return (
<View
style={[styles.introSlide, this.props.myStyle]}
{...this.pan.panHandlers}
>
<View style={styles.introSlideIconView}>
<Icon name={this.props.iconName} size={SLIDE_ICON_SIZE} color="white"/>
</View>
<View style={styles.introSlideTextView}>
<Text style={styles.introSlideTextHeader}> {this.props.headerText} </Text>
<Text style={styles.introSlideText}> {this.props.text} </Text>
</View>
</View>
);
}
}
I did the same to the View component with flex: 1 and i had different result. i get console logs as expected but i can't swipe anymore. So how can i swipe through pages while receiving touch events in parent component ? (In other words, i want two different components to receive touch events, and I'm developing for android)