change button of react native header if data exist - android

I want to check if data exist, If data exist then to show red button and if there is no data then it will show blue button. I tried to do that but its not working . For example Instagram go to DM's button if there are any DM , button change to different color with number of DM's unread and if there is no Dm's then it is simple button.
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
const { notifications } = this.props.notification;
return {
headerRight: (
<View>
{
(notifications.length > 0) ? (
<TouchableOpacity onPress={() => params.handleSave()}>
<Badge>
<Text>{notifications.length}</Text>
</Badge>
</TouchableOpacity>
) : (
<TouchableOpacity onPress={() => params.handleSave()}>
<Ionicons
name="ios-notifications-outline"
style={{ paddingRight: 15 }}
size={24}
color="white"
/>
</TouchableOpacity>
)
}
</View>
)
};
}

create two different styles and condition
style={[navigation.state.yourstate ? styles.selectedButtonStyle : styles.normalButtonStyle]}

Related

How to open default Contact app in react native using Expo?

How to open the default Contact app in react native using Expo?
my requirements are:
Display a button to open the contact book on home screen.
On clicking the button, open the list of contacts in user's phone.
On contact list, each contact item should display the contact's profile picture, full name and the number/type of number(Home/work)
Add a search bar that will allow the user to search contacts by name
Once the user selects a contact, go back to home screen and display the chosen contact's phone number in a text field(not as an alert/toast).
If a contact has multiple phone numbers, allow the user to pick only one phone number.
import React, { useEffect, useState } from "react";
import {
StyleSheet,
View,
Text,
TextInput,
FlatList,
ActivityIndicator,
} from "react-native";
import * as Contacts from "expo-contacts";
export default function App() {
const [allcontacts, setcontact] = useState([]); //say set main state
const [allcontactsfilter, setcontactfilter] = useState([]); // filter state
const [searchcontact, setsearchcontact] = useState("");
const [loading, setloading] = useState(false);
console.log(searchcontact);
useEffect(() => {
(async () => {
const { status } = await Contacts.requestPermissionsAsync();
if (status === "granted") {
const { data } = await Contacts.getContactsAsync({
fields: [
Contacts.Fields.PhoneNumbers,
// Contacts.Fields.Emails
],
});
// console.log("collectio object", data);
if (data.length > 0) {
// console.log("contact hellos", data);
setcontact(data);
setting same data in two-state help to manipulate state when we do filtering
process
setcontactfilter(data);
setloading(false);
}
}
})();
setloading(true);
}, []);
filter function
const filtercontacts = (e) => {
const filtervalue = allcontactsfilter.filter((contact) => { <-- look here at
allcontactsfilter
let lowercase = `${contact.firstName} ${contact.lastName}`.toLowerCase();
let searchlowercase = e.toLowerCase();
return lowercase.indexOf(searchlowercase) > -1;
});
setsearchcontact(setcontact(filtervalue));
};
return (
<View style={styles.container}>
<TextInput
style={{
backgroundColor: "#D5D5D5",
height: 40,
width: "90%",
borderBottomWidth: 0.3,
borderBottomColor: "#ddd",
}}
placeholder="search"
value={searchcontact}
onChangeText={filtercontacts}
/>
{loading ? (
<View>
<ActivityIndicator size={35} color="green" />
</View>
) : null}
<FlatList
data={allcontacts}
keyExtractor={(item, index) => index.toString()}
renderItem={({ item }) => (
<View style={{ minHeight: 70, padding: 5 }}>
<Text>
{/* {
("inside flatlist>>>,....",
console.log(
item.phoneNumbers == undefined || null
? []
: item.phoneNumbers[0]?.number
))
} */}
{item?.firstName == null
? "please update name in your phone contact book"
: item.firstName}
{item?.lastName == null ? null : item.lastName}
</Text>
<Text style={{ color: "red" }}>
{item.phoneNumbers == undefined || null
? []
: item.phoneNumbers[0]?.number}
</Text>
</View>
)}
ListEmptyComponent={() => (
<Text style={{ fontSize: 20, marginVertical: 40 }}>No contact </Text>
)}
/>
{/* {console.log("okstate..", allcontacts)} */}
<Text>Contacts Module Example </Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
});
apply style according to your need.

React Native white background output on Listview

I'm making a list view were I will view a list of some data from my database. But after running the program all I got is white background screen. Does anyone knows the solution?
screen shot
Here is my code
export default class Pasta extends Component {
constructor() {
super()
this.state = {
dataSource: []
}
}
renderItem = ({ item }) => {
return (
<View style = {{flex: 1, flexDirection: 'row'}}>
<View style = {{flex: 1, justifyContent: 'center'}}>
<Text>
{item.menu_desc}
</Text>
<Text>
{item.menu_price}
</Text>
</View>
</View>
)
}
componentDidMount() {
const url = 'http://192.***.***.***:9090/menu'
fetch(url)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
dataSource: responseJson.menu
})
})
}
render() {
return (
<View style = { styles.container }>
<FlatList
data = { this.state.dataSource }
renderItem = {this.renderItem}
/>
</View>
);
}
}
Add extraData prop to your FlatList to cause a re-render
keyExtractor = (item, index) => item.id; // note: id is the unique key for each item
render() {
return (
<FlatList
data = {this.state.dataSource}
renderItem = {this.renderItem}
extraData={this.state}
keyExtractor={this.keyExtractor}
/>
);
}
Also log and verify your data is present. I suggest referring to FlatList docs for more props like keyExtractor etc.

React native multiple button select

Hi I want simple a button select and deselect when I have lots of buttons in one page like toggle select but no other button will effect.
My code like below:
constructor(props) {
super(props);
this.state = {
activeState: [false, false, false]
};
this.buttonPressed = this.buttonPressed.bind(this);
}
buttonPressed(index) {
// I want to update array value true and false.
}
<TouchableOpacity
style={this.state.activeClasses[0] ? styles.rateButton :
styles.rateButtonActive}
onPress={() => this.addActiveClass(0)}>
</TouchableOpacity>
<TouchableOpacity
style={this.state.activeClasses[1] ? styles.rateButton :
styles.rateButtonActive}
onPress={() => this.addActiveClass(1)}>
</TouchableOpacity>
You can suggest me a different process or method by which I can make this.
I don't know if this is exactly what you want, but i'll give it a try:
buttonPressed(index) {
const tmpState = this.state.activeState.map((val, tmpIndex) => {
if (tmpIndex === index) {
return !val;
}
return val;
});
this.setState({ activeState: tmpState });
}

react-Native Change color on selected item in flatlist

I have a flat list that renders several buttons, I want to mark the selected button inside esee flat list, I tried a lot of things but in all of them the flat list mark all the items once I select one, besides that, it does not update until i Update something in the component and save the changes, then it does hot reloading and this is how the marked items are displayed
constructor(props) {
super(props);
this.state = {
pressStatus: false,
};
_onShowUnderlay(){
this.setState({ pressStatus: true });
}
render() {
return (
<FlatList
keyExtractor={this._keyExtractor}
data={this.state.ninosPicker}
renderItem={({item}) => (
<View style={styles.hijos}>
<TouchableHighlight
activeOpacity={1}
underlayColor="#3fa9f5"
onShowUnderlay={this._onShowUnderlay.bind(this)}
style={this.state.pressStatus ? styles.buttonPress : styles.botonsito }
onPress={() => this.setHijo(item.grado, item.grupo)}>
<Text style={this.state.pressStatus ? styles.welcomePress : styles.titBtnGyG }>{item.name}</Text>
</TouchableHighlight>
<TouchableHighlight
activeOpacity={1}
underlayColor="#3fa9f5"
style={this.state.pressStatus ? styles.gradosPress : styles.grados }>
<Text style={this.state.pressStatus ? styles.welcomePress : styles.titBtnGyG }>{item.grado}</Text>
</TouchableHighlight>
<TouchableHighlight
activeOpacity={1}
underlayColor="#3fa9f5"
style={this.state.pressStatus ? styles.grupoPress : styles.grupo }>
<Text style={this.state.pressStatus ? styles.welcomePress : styles.titBtnGyG }>{item.grupo}</Text>
</TouchableHighlight>
</View>
)}/>
You have to take into account that in the coding you are placing a unique state, in this case this.state.pressStatus, what you need is to have in the arrangement in each object a property pressStatus, at the time of executing the action of the button you have to change the state of that button

Remove multiple components in react native

I know how to add and remove a single component by changing the state. But this way wont work if you have multiple components to remove. For instance lets say I have 3 Views. How can I remove them when I click on them.
Example code:
class Example extends Component {
render(){
return (
<View>
<View>
<TouchAbleOpacity onPress={() => this.removeView()}>
<Text>Remove View 1</Text>
</TouchAbleOpacity>
</View>
<View>
<TouchAbleOpacity onPress={() => this.removeView()}>
<Text>Remove View 2</Text>
</TouchAbleOpacity>
</View>
<View>
<TouchAbleOpacity onPress={() => this.removeView()}>
<Text>Remove View 3</Text>
</TouchAbleOpacity>
</View>
</View>
)
}
removeView(){
}
}
Another example will be when I have a ListView with buttons inside. These are buttons to invite a user. When I click on the button I want to hide the button for that specific row in the ListView.
Any suggestions?
Thanks to Giorgos I found a solution for my own question. I created a separate component with a hide function inside the component. Now I can just add this component anywhere in a view or in a listView and when I click on it it will hide. Remember this only hides the component and does not unmount it.
This is just an example so I created a button component.
My Button Component:
class ButtonComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
hide:false
}
}
render() {
return (
<View style={styles.container}>
{this.renderButtonComponent()}
</View>
);
}
renderButtonComponent(){
if(!this.state.hide){
return (
<TouchableOpacity onPress={this.hide.bind(this)}>
<Text>Button</Text>
</TouchableOpacity>
);
}
}
hide(){
this.setState({
hide:true
});
}
}
In my View I just render my Component:
render() {
return (
<View style={styles.container}>
<ButtonComponent/>
<ButtonComponent/>
<ButtonComponent/>
</View>
);
}
You have to use your component's state. Whenever you call setState the component's render() function is triggered again. There based on what the current state is, you can decide what to show and what not. For example:
class Example extends Component {
constructor(props){
// initialize state
this.state = {
isView1Visible: true,
isView2Visible: true,
isView2Visible: true
}
}
render(){
return (
<View>
{ this.renderView1() }
{ this.renderView2() }
{ this.renderView3() }
</View>
)
}
renderView1(){
if(this.state.isView1Visible){
return (
<View>
<TouchAbleOpacity onPress={() => this.setState( {isView1Visible: false} )}>
<Text>Remove View 1</Text>
</TouchAbleOpacity>
</View>
)
}
renderView2(){
if(this.state.isView2Visible){
return (
...
)
}
renderView3(){
if(this.state.isView3Visible){
return (
...
)
}
}
In the above example, you render your view based on the current state. When the button is clicked, you update the state by calling setState() which, like I mentioned before, will trigger another call to render().
With the ListView the approach is the same but the implementation slightly different. What you need to do there is to save your list of items in the state of your component and whenever you want to add/remove an item, you update the list accordingly and then update the state using setState. For example, something similar to this:
constructor(props) {
super(props);
var list = [ ... ]
const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.state = {
dataSource: ds,
items: ds.cloneWithRows(list)
};
}
render() {
return (
<View>
<ListView
dataSource={this.state.items}
renderRow={(rowData) => this.renderRow(rowData) /> } />
</View>
)
}
renderRow(rowData) {
<View>
<TouchAbleOpacity onPress={() => this.updateList()}>
<Text>Remove View 1</Text>
</TouchAbleOpacity>
</View>
}
updateList() {
// do some changes to your list and update the state.
var newItems = ...
this.setState({
items: newItems
})
}
Hope this helps.

Categories

Resources