Passing param properly to a function in React Native - javascript

I'm struggling to pass const navigation = useNavigation(); properly to my outer function.
Currently, I have this 'main' function:
export default function MyDrawer({ route }) {
const nav = useNavigation(); // Use hook here as u will now dont get any error. now pass it as param to above if needed
return (
<NavigationContainer independent={true}>
<Drawer.Navigator
initialRouteName="QR"
drawerContent={props => CustomDrawerContent(props, route)}
>
<Drawer.Screen
name="QR"
component={QR}
initialParams={{ user: route.params.user }}
/>
<Drawer.Screen name="Odabir" component={Odabir} />
</Drawer.Navigator>
</NavigationContainer>
);
}
which handles the drawer logic and routing. I used to declare const Drawer = createDrawerNavigator() in this function:
function CustomDrawerContent({ props, navigation }, route, ) {
// *** Don't use below hook here its wrong to use hooks outside main function if need pass to it as param from main function
// const navigation = useNavigation();
return (
<SafeAreaView style={{ flex: 1 }}>
<View
style={{
height: 150,
alignItems: "center",
justifyContent: "center",
marginTop: Platform.OS === "ios" ? 0 : StatusBar.currentHeight
}}
>
<Image
source={{uri:route.params.user.photoUrl}}
style={{ height: 110, width: 110, borderRadius: 60 }}
/>
</View>
<View style={{ height: 30, alignItems: "center" }}>
<Text style={styles.naslov}>
{route.params.user.name} {route.params.user.lastname}
</Text>
</View>
<View style={{ height: 30, alignItems: "center" }}>
<Text style={styles.naslov}>
{route.params.user.email}
</Text>
</View>
<View style={{ height: 30, alignItems: "center", marginBottom: 10 }}>
<Text style={styles.naslov}></Text>
</View>
<Divider />
<ScrollView style={{ marginLeft: 5 }}>
<TouchableOpacity
style={{ marginTop: 20, marginLeft: 20 }}
onPress={() => props.navigation.navigate("QR")}
>
<View style={{ padding: 10 }}>
<Ionicons name="ios-qr-scanner" size={20} styles={{}}>
<Text style={styles.naslov}> QR</Text>
</Ionicons>
</View>
</TouchableOpacity>
<TouchableOpacity
style={{ marginTop: 20, marginLeft: 20 }}
onPress={() => props.navigation.navigate("Odabir")}
>
<View style={{ padding: 10 }}>
<Ionicons name="ios-qr-scanner" size={20} styles={{}}>
<Text style={styles.naslov}> Odabir</Text>
</Ionicons>
</View>
</TouchableOpacity>
<TouchableOpacity
style={{ marginTop: 20, marginLeft: 20 }}
onPress={() => props.navigation.navigate("Odabir")}
>
<View style={{ padding: 10 }}>
<Ionicons name="ios-qr-scanner" size={20} styles={{}}>
<Text style={styles.naslov}> Odabir</Text>
</Ionicons>
</View>
</TouchableOpacity>
</ScrollView>
</SafeAreaView>
);
}
Which handles the onPress routing to different components. I've had to move the const nav = useNavigation(); because of how hooks work and the process of catching data from the Google API.
My question is how do I properly pass the param back to the MyDrawer function so the navigation works again? The error I currently get is TypeError: undefined is not an object(evaluating 'props.navigation')

update code:
export default function MyDrawer({ route }) {
const nav = useNavigation(); // Use hook here as u will now dont get any error. now pass it as param to above if needed
return (
<NavigationContainer independent={true}>
<Drawer.Navigator
initialRouteName="QR"
drawerContent={props => <CustomDrawerContent {...props} {...{route}} />}
>
<Drawer.Screen
name="QR"
component={QR}
initialParams={{ user: route.params.user }}
/>
<Drawer.Screen name="Odabir" component={Odabir} />
</Drawer.Navigator>
</NavigationContainer>
);
}
Drawer Content
const CustomDrawerContent = ({navigation, route}) => {
// *** Don't use below hook here its wrong to use hooks outside main function if need pass to it as param from main function
// const navigation = useNavigation();
return (
<SafeAreaView style={{ flex: 1 }}>
<View
style={{
height: 150,
alignItems: "center",
justifyContent: "center",
marginTop: Platform.OS === "ios" ? 0 : StatusBar.currentHeight
}}
>
<Image
source={{uri:route.params.user.photoUrl}}
style={{ height: 110, width: 110, borderRadius: 60 }}
/>
</View>
<View style={{ height: 30, alignItems: "center" }}>
<Text style={styles.naslov}>
{route.params.user.name} {route.params.user.lastname}
</Text>
</View>
<View style={{ height: 30, alignItems: "center" }}>
<Text style={styles.naslov}>
{route.params.user.email}
</Text>
</View>
<View style={{ height: 30, alignItems: "center", marginBottom: 10 }}>
<Text style={styles.naslov}></Text>
</View>
<Divider />
<ScrollView style={{ marginLeft: 5 }}>
<TouchableOpacity
style={{ marginTop: 20, marginLeft: 20 }}
onPress={() => props.navigation.navigate("QR")}
>
<View style={{ padding: 10 }}>
<Ionicons name="ios-qr-scanner" size={20} styles={{}}>
<Text style={styles.naslov}> QR</Text>
</Ionicons>
</View>
</TouchableOpacity>
<TouchableOpacity
style={{ marginTop: 20, marginLeft: 20 }}
onPress={() => props.navigation.navigate("Odabir")}
>
<View style={{ padding: 10 }}>
<Ionicons name="ios-qr-scanner" size={20} styles={{}}>
<Text style={styles.naslov}> Odabir</Text>
</Ionicons>
</View>
</TouchableOpacity>
<TouchableOpacity
style={{ marginTop: 20, marginLeft: 20 }}
onPress={() => props.navigation.navigate("Odabir")}
>
<View style={{ padding: 10 }}>
<Ionicons name="ios-qr-scanner" size={20} styles={{}}>
<Text style={styles.naslov}> Odabir</Text>
</Ionicons>
</View>
</TouchableOpacity>
</ScrollView>
</SafeAreaView>
);
}

Related

How to update text using TextInput

I'm having some troubles trying to figure out how to edit a text thats already been made.
I have done most of the things and the one i'm stuck at is the button that updates the text to the new updated text. I can see the updated text when I use console.log but it doesn't update the text. Thats still the same. Below you can see the full code and I think the updateTodo function is done wrong.
export default function App() {
const [updateTaskId, setUpdateTaskId] = useState('');
const [updateTaskTitle, setUpdateTaskTitle] = useState('');
const [todos, setTodos] = useState([]);
const updateTodo = () => {
const todoAsync = [
...todos,
{
key: updateTaskId,
name: updateTaskTitle,
},
];
setTodos(todoAsync);
};
const renderitem = ({item}) => {
return (
<View
style={{
flex: 1,
backgroundColor: colors.card,
margin: 10,
elevation: 1,
borderRadius: 10,
padding: 10,
}}>
<View style={{flexDirection: 'row'}}>
<Fontisto
name={item.isChecked ? 'checkbox-active' : 'checkbox-passive'}
size={20}
color={colors.text}
onPress={() => checkTodo(item.key)}
/>
<TouchableOpacity
onLongPress={() => {
setUpdateModal(true);
setUpdateTaskTitle(item.name);
}}>
<Text
style={{
color: colors.text,
marginLeft: 20,
marginRight: 20,
}}>
{item.name}
</Text>
</TouchableOpacity>
</View>
<View style={{flexDirection: 'row', marginTop: 10}}>
<Fontisto name="date" size={20} color={colors.text} />
<Text style={{marginLeft: 20, color: colors.text}}>{item.date}</Text>
</View>
<View
style={{
marginTop: 10,
flexDirection: 'row',
justifyContent: 'space-between',
}}>
<Feather
name={item.notification ? 'bell-off' : 'bell'}
size={20}
color={colors.text}
onPress={() => checkNotification(item.key)}
/>
<Fontisto
name="trash"
size={20}
color={colors.text}
onPress={() => {
setModalVisible(true);
setDetails(item);
}}
/>
</View>
</View>
);
};
return (
<View style={{flex: 1, backgroundColor: colors.background}}>
<Modal
hardwareAccelerated={true}
animationType="fade"
transparent={true}
visible={updateModal}
onRequestClose={() => {
setUpdateModal(!updateModal);
}}>
<View
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'rgba(0,0,0,0.8)',
}}>
<View
style={{
backgroundColor: colors.Modal,
padding: 35,
borderRadius: 10,
width: '80%',
height: '40%',
}}>
<View style={{}}>
<TextInput
style={{backgroundColor: colors.background, marginTop: 10}}
onChangeText={name => setUpdateTaskTitle(name)}
value={updateTaskTitle}
/>
</View>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-evenly',
marginTop: 50,
}}>
<TouchableOpacity
onPress={() => {
setUpdateModal(false);
setUpdateTaskTitle('');
}}>
<Text>Close</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
setUpdateModal(false);
updateTodo(...todos, {name: updateTaskTitle});
setUpdateTaskTitle('');
console.log(updateTaskTitle);
}}>
<Text>Update</Text>
</TouchableOpacity>
</View>
</View>
</View>
</Modal>
<Modal
hardwareAccelerated={true}
animationType="fade"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
setModalVisible(!modalVisible);
}}>
<View
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'rgba(0,0,0,0.8)',
}}>
<View
style={{
backgroundColor: colors.Modal,
padding: 35,
borderRadius: 10,
width: '80%',
height: '40%',
}}>
<View>
<Text style={{fontSize: 20, color: colors.text}}>Delete?</Text>
</View>
<View
style={{
flexDirection: 'row',
marginTop: 15,
}}>
<Text style={{color: colors.text}}>Completed: </Text>
<Fontisto
style={{marginLeft: 20}}
name={
details.isChecked ? 'checkbox-active' : 'checkbox-passive'
}
size={15}
color={colors.text}
/>
</View>
<View style={{flexDirection: 'row', marginTop: 20}}>
<Text style={{color: colors.text}}>Title: </Text>
<Text
numberOfLines={1}
style={{marginLeft: 15, marginRight: 15, color: colors.text}}>
{details.name}
</Text>
</View>
<Text style={{marginTop: 20, color: colors.text}}>
Created: {details.date}
</Text>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-evenly',
marginTop: 30,
}}>
<TouchableOpacity
onPress={() => {
setModalVisible(false);
setDetails('');
}}>
<Text style={{color: colors.text}}>Close</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
deleteTodo(details.key);
setModalVisible(false);
setDetails('');
}}>
<Text style={{color: colors.text}}>Delete</Text>
</TouchableOpacity>
</View>
</View>
</View>
</Modal>
<View
style={{
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
padding: 20,
backgroundColor: colors.Textinput,
elevation: 12,
}}>
<TextInput
style={{
flex: 1,
backgroundColor: '#fff',
borderTopLeftRadius: 5,
borderBottomLeftRadius: 5,
}}
placeholder="What Tododay?"
placeholderTextColor="#000"
onChangeText={value => setTitle(value)}
value={title}
autoCapitalize="words"
/>
<Entypo
style={{
marginLeft: 1,
padding: 13,
backgroundColor: '#fff',
height: 49,
borderTopRightRadius: 5,
borderBottomRightRadius: 5,
}}
name="add-to-list"
size={25}
color="#000"
onPress={() => addTodo()}
/>
</View>
<View style={{flex: 1}}>
<FlatList
data={todos}
renderItem={renderitem}
ListEmptyComponent={emptyListComponent}
/>
</View>
</View>
);
}
Here is what you need to do.
make a copy of all todos
filter out the todo that you are about to update out of the todos array
concat a new todo with the new text to the array of todos
it should render as expected
const updateTodo = () => {
const todoAsync = [
...todos,
].filter((item) => item.id !== updateTaskId).concat([{
key: updateTaskId,
name: updateTaskTitle,
}])
setTodos(todoAsync);
};
Try this if you want to keep the same todo on the screen but only update the object key for name.
const updateTodo = () => {
const todoAsync = [
...todos,
].map((item) => {
const { key } = item;
if(key === updateTaskId} {
// return updated object
return {
key,
name: updateTaskTitle,
}
}
else return item;
}
setTodos(todoAsync);
};

react native firebase async await parellel with promise.all

import fire from '../config/fire';
const db = fire.firestore();
class InitialDb extends Component {
constructor(props) {
super(props);
this.state = {
schools: '',
students: '',
};
}
async componentDidMount() {
const { size: schools } = await db.collection('schools').get();
const { size: students } = await db.collection('students').get();
this.setState({ schools, students});
}
render() {
return (
<SafeAreaView>
{/* <StatusBar translucent backgroundColor='#1b75ce' />
<HC title='Dashboard' /> */}
<BackButton />
<View style={{ paddingTop: 10, marginBottom: 20 }}>
<View style={{ flexDirection: 'row' }}>
<View style={styles.widthstyle}>
<TouchableOpacity>
<Card>
<CardItem>
<Body>
<View style={{ flexDirection: 'row' }}>
<Image
style={{ width: 30, height: 30 }}
source={require('../assets/schools.png')}
/>
<Text style={{ textAlign: 'center' }}>
Schools:{this.state.schools}
</Text>
</View>
</Body>
</CardItem>
</Card>
</TouchableOpacity>
</View>
<View style={styles.widthstyle}>
<TouchableOpacity>
<Card>
<CardItem>
<Body>
<View style={{ flexDirection: 'row' }}>
<Image
style={{ width: 30, height: 30 }}
source={require('../assets/asd.png')}
/>
<Text style={{ textAlign: 'center' }}>
Students:{this.state.students}
</Text>
</View>
</Body>
</CardItem>
</Card>
</TouchableOpacity>
</View>
</View>
<View
style={{ flexDirection: 'row' }}
// style={styles.basic1Style}
>
<View style={styles.widthstyle}>
<TouchableOpacity>
<Card>
<CardItem>
<Body>
<View style={{ flexDirection: 'row' }}>
<Image
style={{ width: 30, height: 30 }}
source={require('../assets/def.png')}
/>
<Text style={{ textAlign: 'center' }}>
Office:50
</Text>
</View>
</Body>
</CardItem>
</Card>
</TouchableOpacity>
</View>
<View style={styles.widthstyle}>
<TouchableOpacity>
<Card>
<CardItem>
<Body>
<View style={{ flexDirection: 'row' }}>
<Image
style={{ width: 30, height: 30 }}
source={require('../assets/abc.png')}
/>
<Text style={{ textAlign: 'center' }}>Attended:50</Text>
</View>
</Body>
</CardItem>
</Card>
</TouchableOpacity>
</View>
</View>
</View>
{/* <Text style={{ textAlign: "center" }}>
Swipe from left to right for menu
</Text> */}
<View style={{ marginBottom: 2 }}>
<Text style={{ textAlign: 'center', fontSize: 20, marginBottom: 5 }}>
Search
</Text>
</View>
<Form style={{ marginLeft: 20 }}>
<View style={{ flexDirection: 'row' }}>
<Item style={{ paddingLeft: 20, width: '40%' }}>
<Label style={{ textAlign: 'left' }}>Division</Label>
<Input />
</Item>
<Item style={{ paddingLeft: 20, width: '40%' }}>
<Label style={{ textAlign: 'left' }}>Area</Label>
<Input />
</Item>
</View>
<View style={{ flexDirection: 'row', paddingTop: 20 }}>
<Item style={{ paddingLeft: 20, width: '40%' }}>
<Label style={{ textAlign: 'left' }}>Gang</Label>
<Input />
</Item>
<Item
style={{
borderBottomColor: 'white',
}}
>
<Button info style={{ marginLeft: 25 }}>
<Text> Search </Text>
</Button>
</Item>
</View>
</Form>
{/*<View style={{ flex: 1, marginTop: 3, left: 0, right: 0, bottom: 0 }}>
<MapView
initialRegion={{
latitude: 12.93092,
longitude: 77.602156,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
style={styles.mapStyle}
></MapView>
</View>
*/}
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
basic1Style: {
// flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'row',
},
widthstyle: {
width: Dimensions.get('window').width / 2,
},
mapStyle: {
position: 'absolute',
top: 3,
left: 0,
right: 0,
bottom: 0,
},
});
export default InitialDb;
**This code above is working synchronously and also in series manner. I want this to be in async and await because this is freezing the UI. And also it should update the all 2 state objects after getting the size of all those 2 firestore collections using promise.all.
Here I have updated the code Please check it again **
PROBLEM
The problem here is basically your firebase is initializing on every hot-module reload. You only need to initialize once per App.
So basically, you could wrap your firebase initialization with try-catch and swallow the error.
try {
firebase.initializeApp({
/** config here **/
});
} catch(err) {
console.log(err);
}

trying to get a nested array work with react native flat list

so i got this object that i pass as data to my react native flatlist
<FlatList
extraData = {this.state}
data = {this.state.data_n1}>
renderItem = {({item, index}) => {
this.state.data_n2.forEach(aux => {
if(item.id == aux.id) {
return(<View><Text>Display first stuff</Text></View>);
} else {
return(<View><Text>Display second stuff</Text></View>);
}
}
}
/>
the whole idea is compare both objects, if the data_n2 contains the same id from the data_n1, the display the data from the data_n2, if not, just display from data_n1, problem is, i'm displaying this whenever i click on a calendar strip, so if i click on day june 1st, that day should display data_n2, if i click on day june 2nd, THAT one should display the data_n1.
does this work with flatlist or virtualizedlist (if i had to swap), or i need to render a flatlist for each data?
Edit: tested hao wu answer, but got this
Edit n2: i'll post the code, but keep in mind data_n1 is this.state.listaImputacionDia and this.state.listaImputacionDia is data_n2
this is the calendar strip code
<CalendarStrip
calendarHeaderStyle={{
fontSize: rfv(18),
fontWeight: "normal",
fontStyle: "normal",
letterSpacing: 0,
textAlign: "left",
color: "#707070",
paddingBottom: hp('4.5%')
}}
selectedDate={this.state.selectedDate}
onDateSelected={async (date) => {
await HoursReportHistoryBusiness.GetInstance().getListHoursReportRequest();
this.setState({ selectedDate: moment(date).format('YYYY-MM-DD') });
this.setViewHourHistory();
console.log(this.state.listaImputacionDia);
}}
minDate={moment().subtract(3, 'days')}
maxDate={moment().add(3,'days')}
startingDate={moment().subtract(3, 'days')}
useIsoWeekday={false}
style={{paddingTop: hp('1.5%'), paddingBottom: hp('2.7%'), backgroundColor: '#ffffff'}}
highlightDateNameStyle={{color: '#1062cc'}}
highlightDateNumberStyle={{color: '#1062cc'}}
disabledDateNumberStyle={{color: '#f21927'}}
disabledDateNameStyle={{color: '#f21927'}}
customDatesStyles={this.customDatesStyle}
dateNameStyle={{color: '#c4c4c4'}}
dateNumberStyle={{color: '#c4c4c4'}}
disabledDateOpacity={1}
/>
this is the flatlist
<FlatList
extraData={this.state.listaImputacionDia}
data={this.state.dataSource}//{DataManager.FavoriteList[moment(this.state.selectedDate).format('YYYY-MM-DD')]}
renderItem={({ item, index }) => {
if (this.state.listaImputacionDia.length != 0) {
const found = this.state.listaImputacionDia.filter(aux => item.id == aux.IdProyecto);
//this.state.listaImputacionDia.forEach(aux => {
if (found/*item.id == aux.IdProyecto*/) {
console.log('la wea' + found);
return (
<View style={{ marginTop: hp('2%') }}>
<TouchableOpacity style={} onPress={() => this.toggleExpanded()}>
<View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between' }}>
<View style={{ flexDirection: 'column', justifyContent: 'center' }}>
<Text numberOfLines={2} ellipsizeMode="tail" style={}>{found.Title}</Text>
<Text style={}>{`ID ${found.Id} - ${found.Cliente}`}</Text>
{
!found.fav ?
<Text style={}>No favorito</Text>
: null
}
</View>
<View style={{ flexDirection: 'column', justifyContent: 'center' }}>
<View style={{ flexDirection: 'row', marginRight: wp('3.4%') }}>
<Text style={}>{`${found.HorasTrabajadas}h`}</Text>
<Image style={{ marginTop: hp('1%'), marginLeft: wp('3.7%') }} source={this.state.isCollapsed ? Images.expandible : Images.collapsible} />
</View>
</View>
</View>
</TouchableOpacity>
<Collapsible style={{
alignSelf: 'center',
width: wp('95.7%'),
backgroundColor: "#ffffff",
}} collapsed={this.state.isCollapsed}>
<View>
<View style={{ flexDirection: 'row' }}>
<Text style={}>Etapa</Text>
<Text style={}>Horas</Text>
</View>
<View style={{ flexDirection: 'row' }}>
<ModalDropdown
adjustFrame={style => {
style.top = (Platform.OS === 'ios' ? style.top : style.top - StatusBar.currentHeight);
return style;
}}
dropdownTextStyle={styles.dropdownTextStyle}
dropdownTextHighlightStyle={styles.dropdownTextHighlightStyle}
dropdownStyle={styles.dropdownStageStyle}
defaultValue={'Seleccionar'}
style={styles.dropStageStyle}
textStyle={{
padding: 0,
margin: 0,
fontSize: rfv(16),
paddingVertical: hp('1.2%'),
fontWeight: 'normal',
fontStyle: 'normal',
textAlign: 'left',
color: found.etapa != '' ? '#1a1a1a' : '#c4c4c4',
}}
//onSelect={(index, value) => this.setState({SeleccionClientes: value})}
//options={Object.keys(this.state.items)}
onSelect={(index, value) => this.setState({ SeleccionClientes: value })}
options={DataManager.ListEtapa}
/>
<View style={styles.InputContainerHours}>
<Text style={styles.InputTextHours}>{found.HorasTrabajadas}</Text>
</View>
<TouchableOpacity style={{ marginTop: hp('0.5%'), marginLeft: wp('5.5%') }} onPress={() => this.props.onSubstract}>
<Image source={Images.menos_hora} />
</TouchableOpacity>
<TouchableOpacity style={{ marginTop: hp('0.5%'), marginLeft: wp('2%') }} onPress={() => this.props.onAdd}>
<Image source={Images.mas_hora} />
</TouchableOpacity>
</View>
<Text style={}>Observaciones</Text>
<Input
autoCapitalize="none"
maxLength={100}
inputContainerStyle={styles.InputContainerComentarioOnBlur}
containerStyle={styles.InputComentario}
inputStyle={styles.InputTextHoursRInput}
placeholderTextColor={'#c4c4c4'}
placeholder="(Opcional)"
onChangeText={value => this.setState({})}
/>
<TouchableOpacity style={{ alignItems: 'flex-end', alignSelf: 'flex-end' }}>
<Text style={}>Agregar etapa</Text>
</TouchableOpacity>
</View>
</Collapsible>
</View>
)
}
else {
console.log('no encontro un favorito');
return (
<View style={{ marginTop: hp('2%') }}>
<TouchableOpacity style={{
alignSelf: 'center',
width: wp('95.7%'),
height: hp('10%'),
backgroundColor: "#ffffff",
}} onPress={() => this.toggleExpanded()}>
<View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between' }}>
<View style={{ flexDirection: 'column', justifyContent: 'center' }}>
<Text numberOfLines={2} ellipsizeMode="tail" style={} >{found.title}</Text>
<Text style={}>{`ID ${found.id} - ${found.cliente}`}</Text>
{
!item.fav ?
<Text style={}>No favorito</Text>
: null
}
</View>
<View style={{ flexDirection: 'column', justifyContent: 'center' }}>
<View style={{ flexDirection: 'row', marginRight: wp('3.4%') }}>
<Text style={}>{`${20}h`}</Text>
<Image style={{ marginTop: hp('1%'), marginLeft: wp('3.7%') }} source={this.state.isCollapsed ? Images.expandible : Images.collapsible} />
</View>
</View>
</View>
</TouchableOpacity>
<Collapsible style={{
alignSelf: 'center',
width: wp('95.7%'),
backgroundColor: "#ffffff",
}} collapsed={this.state.isCollapsed}>
<View>
<View style={{ flexDirection: 'row' }}>
<Text style={}>Etapa</Text>
<Text style={}>Horas</Text>
</View>
<View style={{ flexDirection: 'row' }}>
<ModalDropdown
adjustFrame={style => {
style.top = (Platform.OS === 'ios' ? style.top : style.top - StatusBar.currentHeight);
return style;
}}
dropdownTextStyle={styles.dropdownTextStyle}
dropdownTextHighlightStyle={styles.dropdownTextHighlightStyle}
dropdownStyle={styles.dropdownStageStyle}
defaultValue={'Seleccionar'}
style={styles.dropStageStyle}
textStyle={}
//onSelect={(index, value) => this.setState({SeleccionClientes: value})}
//options={Object.keys(this.state.items)}
onSelect={(index, value) => this.setState({ SeleccionClientes: value })}
options={DataManager.ListEtapa}
/>
<View style={styles.InputContainerHours}>
<Text style={styles.InputTextHours}>{found.horas}</Text>
</View>
<TouchableOpacity style={{ marginTop: hp('0.5%'), marginLeft: wp('5.5%') }} onPress={() => this.props.onSubstract}>
<Image source={Images.menos_hora} />
</TouchableOpacity>
<TouchableOpacity style={{ marginTop: hp('0.5%'), marginLeft: wp('2%') }} onPress={() => this.props.onAdd}>
<Image source={Images.mas_hora} />
</TouchableOpacity>
</View>
<Text style={}>Observaciones</Text>
<Input
autoCapitalize="none"
maxLength={100}
inputContainerStyle={styles.InputContainerComentarioOnBlur}
containerStyle={styles.InputComentario}
inputStyle={styles.InputTextHoursRInput}
placeholderTextColor={'#c4c4c4'}
placeholder="(Opcional)"
onChangeText={value => this.setState({})}
/>
<TouchableOpacity style={{ alignItems: 'flex-end', alignSelf: 'flex-end' }}>
<Text style={}>Agregar etapa</Text>
</TouchableOpacity>
</View>
</Collapsible>
</View>
);
}
//})
}
else {
console.log('imputacion por dia esta vacio');
return (
<View style={{ marginTop: hp('2%') }}>
<TouchableOpacity style={{
alignSelf: 'center',
width: wp('95.7%'),
height: hp('10%'),
backgroundColor: "#ffffff",
}} onPress={() => this.toggleExpanded()}>
<View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between' }}>
<View style={{ flexDirection: 'column', justifyContent: 'center' }}>
<Text numberOfLines={2} ellipsizeMode="tail" style={}>{item.title}</Text>
<Text style={}>{`ID ${item.id} - ${item.cliente}`}</Text>
{
!item.fav ?
<Text style={}>No favorito</Text>
: null
}
</View>
<View style={{ flexDirection: 'column', justifyContent: 'center' }}>
<View style={{ flexDirection: 'row', marginRight: wp('3.4%') }}>
<Text style={}>{`${10}h`}</Text>
<Image style={{ marginTop: hp('1%'), marginLeft: wp('3.7%') }} source={this.state.isCollapsed ? Images.expandible : Images.collapsible} />
</View>
</View>
</View>
</TouchableOpacity>
<Collapsible style={{
alignSelf: 'center',
width: wp('95.7%'),
backgroundColor: "#ffffff",
}} collapsed={this.state.isCollapsed}>
<View>
<View style={{ flexDirection: 'row' }}>
<Text style={}>Etapa</Text>
<Text style={}>Horas</Text>
</View>
<View style={{ flexDirection: 'row' }}>
<ModalDropdown
adjustFrame={style => {
style.top = (Platform.OS === 'ios' ? style.top : style.top - StatusBar.currentHeight);
return style;
}}
dropdownTextStyle={styles.dropdownTextStyle}
dropdownTextHighlightStyle={styles.dropdownTextHighlightStyle}
dropdownStyle={styles.dropdownStageStyle}
defaultValue={'Seleccionar'}
style={styles.dropStageStyle}
textStyle={}
//onSelect={(index, value) => this.setState({SeleccionClientes: value})}
//options={Object.keys(this.state.items)}
onSelect={(index, value) => this.setState({ SeleccionClientes: value })}
options={DataManager.ListEtapa}
/>
<View style={styles.InputContainerHours}>
<Text style={styles.InputTextHours}>{item.horas}</Text>
</View>
<TouchableOpacity style={{ marginTop: hp('0.5%'), marginLeft: wp('5.5%') }} onPress={() => this.props.onSubstract}>
<Image source={Images.menos_hora} />
</TouchableOpacity>
<TouchableOpacity style={{ marginTop: hp('0.5%'), marginLeft: wp('2%') }} onPress={() => this.props.onAdd}>
<Image source={Images.mas_hora} />
</TouchableOpacity>
</View>
<Text style={}>Observaciones</Text>
<Input
autoCapitalize="none"
maxLength={100}
inputContainerStyle={styles.InputContainerComentarioOnBlur}
containerStyle={styles.InputComentario}
inputStyle={styles.InputTextHoursRInput}
placeholderTextColor={'#c4c4c4'}
placeholder="(Opcional)"
onChangeText={value => this.setState({})}
/>
<TouchableOpacity style={{ alignItems: 'flex-end', alignSelf: 'flex-end' }}>
<Text style={}>Agregar etapa</Text>
</TouchableOpacity>
</View>
</Collapsible>
</View>
);
}
}}
/>
forEach only returns undefined, no matter what you return in the function.
You could find the element first, and then render it conditionally:
<FlatList
extraData={this.state.data_n2}
data={this.state.data_n1}>
renderItem = {({ item, index }) => {
const found = this.state.data_n2.find(aux => item.id == aux.id);
if (found) {
return (<View><Text>Display first stuff: {found.id}</Text></View>);
} else {
return (<View><Text>Display second stuff: {item.id}</Text></View>);
}
}}
/>
If there are possibly multiple matches:
<FlatList
extraData={this.state}
data={this.state.data_n1}>
renderItem = {({ item, index }) => {
const found = this.state.data_n2.filter(aux => item.id == aux.id);
if (found.length > 0) {
return (
<View>{
found.map(e => (<View><Text>Display first stuff: {e.id}</Text></View>))
}</View>
);
} else {
return (<View><Text>Display second stuff</Text></View>);
}
}}
/>

Style in react-native

I'm trying to adjust the homepage but I don't know how to change the position of the Text.
I have this code:
return (
<View style={style.container}>
<View style={style.page}>
<Icon
name="user-circle"
color="#56cbbe"
size={70}
onPress={() => Actions.visualizzaprofilo({ cf: Username })}
/>
<Text
style={{
paddingBottom: 15,
textAlign: "center",
fontSize: 15,
color: "#56cbbe",
fontWeight: "bold"
}}
onPress={() => Actions.visualizzaprofilo({})}
>
Visualizza il Profilo
</Text>
<Text style={{ textAlign: "center", fontSize: 20 }}>
{"Benvenuto"}
</Text>
<Text
style={{
textAlign: "center",
fontSize: 20,
color: "#56cbbe",
fontWeight: "bold"
}}
>
<TouchableOpacity
style={[style.button, style.buttonOK]}
onPress={() => this.checkFunction()}
>
<Text style={style.buttonTesto}>Inizia</Text>
</TouchableOpacity>
{this.modProfilo({ })}
{this.eliminaProfilo({ })}
{this.sensorCheck()}
{this.logout()}
</View>
</View>
Where for example modProfilo (and also the other have the same style):
modProfilo({}) {
<Text
style={{ color: "#56cbbe", paddingTop: 20 }}
onPress={() => Actions.modificaprofilo({ })}
>
MODIFICA PROFILO
</Text>
I need to transform the first image in the second one, how can i Do??
Enclose them in a view with flexDirection set to row and justifyContent set to space-between:
return (
<View style={style.container}>
...
<View style={{flexDirection:'row', justifyContent:'space-between'}}>
{this.modProfilo({ })}
{this.eliminaProfilo({ })}
{this.sensorCheck()}
{this.logout()}
</View>
...
</View>
flexDirection: 'row'
This will do the required job. BY default the flex direction is vertical. U just need to change into horizontal.
Added a View (let id be OuterView) and add button inside it. Add below styles in your code:
OuterView: {
flex: 1,
flexDirection: 'row',
},
buttonsStyle: {
flex: 1,
}

How to make button disabled if all checkbox are unchecked in react native

There are 3 check boxes and I have to make one check box mandatory . Like if all checkbox are un checked then button should be disabled . Please help me for that . How I can do .
<View style={{ flexDirection: 'row', paddingLeft: 15 }}>
<View style={{ flex: 1 }}>
<CheckBox color="#00678f"
checked={this.state.notification.isContactByPost}
onPress={() => this.handleChange('isContactByPost')}
/>
</View>
<View style={{ flex: 1 }}>
<Text style={{ fontSize: 14 }}>Post</Text>
</View>
<View style={{ flex: 1 }}>
<CheckBox color="#00678f"
checked={this.state.notification.isContactByEmail}
onPress={() => this.handleChange('isContactByEmail')}
/>
</View>
<View style={{ flex: 1 }}>
<Text style={{ fontSize: 14 }}>Email</Text>
</View>
<View style={{ flex: 1 }}>
<CheckBox color="#00678f"
checked={this.state.notification.isContactBySms}
onPress={() => this.handleChange('isContactBySms')}
/>
</View>
<View style={{ flex: 1 }}>
<Text style={{ fontSize: 14 }}>SMS</Text>
</View>
</View>
<View style={{ marginTop: 50 }}>
<PrimaryBtn
label={'submit'}
disabled={false}
onPress={() => this.OnButtonClick(this.state.notification)}
/>
</View>
</View>
Thanks
This is how you can do it
<PrimaryBtn label={'submit'} disabled={!this.state.notification.isContactByPost &&
!this.state.notification.isContactByEmail &&
!this.state.notification.isContactBySms} onPress={() =>
this.OnButtonClick(this.state.notification)} />
Hope this helps
Try this (to make it more simple i removed redundant parts) =>
const {isContactByPost, isContactByEmail, isContactBySms} = this.state.notification
const isButtonDisabled = !(isContactByPost || isContactByEmail || isContactBySms)
<PrimaryBtn disabled={isButtonDisabled} /> // don't forget your others props :)
render(){
const {isContactByPost,isContactByEmail,isContactBySms } = this.state.notification;
return (
<PrimaryBtn
label={'submit'}
disabled={!(isContactByPost || isContactByEmail || isContactBySms)}
onPress={() => this.OnButtonClick(this.state.notification)}
/>
);
}

Categories

Resources