How to press a component via ref? - react-native

I'm trying to open the datepicker using onSubmitEditing={() => this.refs.date.press()} but press, onPress or click aren't functions. Which is the function to press a component via ref?
<View>
<Text>Apellido</Text>
<TextInput ref="lastname" onSubmitEditing={() => this.refs.date.click()} onChangeText={(lastname) => this.setState({ lastname })} returnKeyType="next" />
</View>
<View>
<Text>Fecha nacimiento</Text>
<DatePicker
ref="date"
date={this.state.date}
onDateChange={(date) => this.setState({ date })}
/>
</View>

The solution is call to the function that shows the DatePicker internally.
SignUp.js
<View>
<Text>Apellido</Text>
<TextInput ref="lastname" onSubmitEditing={() => this.refs.date.showPicker()} onChangeText={(lastname) => this.setState({ lastname })} returnKeyType="next" />
</View>
<View>
<Text>Fecha nacimiento</Text>
<DatePicker
ref="date"
date={this.state.date}
onDateChange={(date) => this.setState({ date })}
/>
</View>
DatePicker.js
import React, { Component } from 'react';
import moment from "moment";
import {
DatePickerAndroid,
Text,
TouchableWithoutFeedback,
View,
} from 'react-native';
export default class DatePicker extends Component {
constructor(props) {
super(props);
this.state = {
date: props.date,
text: moment(props.date).format('DD/MM/YY'),
maxDate: props.maxDate,
minDate: props.minDate,
};
}
async showPicker() {
try {
const {action, year, month, day} = await DatePickerAndroid.open(
{ date: this.props.date, maxDate: this.props.maxDate, minDate: this.props.minDate }
);
if (action !== DatePickerAndroid.dismissedAction) {
var date = new Date(year, month, day);
this._onDateChange(date);
}
} catch ({code, message}) {
console.warn('Error in example ' + message);
}
}
_onDateChange(date) {
var text = moment(date).format('DD/MM/YY');
this.props.onDateChange(date);
this.setState({
text,
date
});
}
render() {
return (
<TouchableWithoutFeedback onPress={() => this.showPicker()}>
<View >
<Text style={this.props.style}>{this.state.text}</Text>
</View>
</TouchableWithoutFeedback>
);
}
}
DatePicker.defaultProps = {
date: new Date(),
minDate: new Date(1900, 1, 1),
maxDate: new Date(2016, 11, 1)
};

Related

React native pedometer is not a counting

Hi everyone I'm trying to make an pedometer app. I installed theese packages.
"react-native-pedometer": "^0.0.7",
"react-native-pedometer-ios-android"//then i deleted it
"#t2tx/react-native-universal-pedometer" // and installed it
and the all exmaple code
import React, {Component} from 'react';
import {View, Text, StyleSheet, Button} from 'react-native';
import Pedometer, {
PedometerInterface,
} from '#t2tx/react-native-universal-pedometer';
// interface PedoResult : PedometerInterface | string | null;
export default class PCount extends Component {
constructor(props) {
super(props);
this.state = {
data: {},
error: 'none',
};
}
check = () => {
Pedometer.isStepCountingAvailable((error, result) => {
console.log(error, result);
this.setState({
data: {result: result + ''},
error,
});
});
};
start = () => {
Pedometer.startPedometerUpdatesFromDate(
new Date().setHours(0, 0, 0, 0),
(data) => {
this.setState({
data: data || {},
error: '-',
});
},
);
};
stop = () => {
Pedometer.stopPedometerUpdates();
this.setState({
data: {state: 'stoped'},
error: '-',
});
};
load = () => {
const start = new Date();
start.setHours(0, 0, 0, 0);
const end = new Date();
Pedometer.queryPedometerDataBetweenDates(
start.getTime(),
end.getTime(),
(error, data: PedometerInterface | null) => {
console.log(error);
console.log(data);
this.setState({
data: data || {},
error,
});
},
);
};
render() {
return (
<View style={styles.container}>
<View style={styles.row}>
<View style={styles.rowItem}>
<Button title=" ? " onPress={this.check} />
</View>
<View style={styles.rowItem}>
<Button title=" ▶︎ " onPress={this.start} />
</View>
<View style={styles.rowItem}>
<Button title=" ■ " onPress={this.stop} />
</View>
<View style={styles.rowItem}>
<Button title=" ◎ " onPress={this.load} />
</View>
</View>
<View style={[styles.row, styles.rowItem]}>
<Text>ERROR: {this.state.error}</Text>
</View>
<View style={styles.rowItem}>
<Text>DATA:</Text>
</View>
{Object.keys(this.state.data).map((key) => {
return (
<View key={key} style={styles.detailItem}>
<Text>
{key}: {this.state.data[key]}
</Text>
</View>
);
})}
</View>
);
}
}
Also this is not my code i copied it from github repo
https://github.com/t2tx/pedometer_example/blob/master/Components/Debug/PedometerComponent.tsx
This is not working. Is there any other way to make this happen. Thank you

How to deal with delay api response in react native using redux?

Im building a react-native app, which when the user try to signIn, I invoike firebase.CreateUser and then an api from firebase function to create that user in my database (Firebase Real-Time). The problem is that when the componentDidUpdate is executed, I still don't have the result from my firebaseFunction, then my props only update if I tap in screen. I would like to know how to deal with that.
Im using redux.
Follow my code:
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Button, Image,Alert} from 'react-native';
import logo from '../../asserts/logo.png'
import { TouchableOpacity, TextInput } from 'react-native-gesture-handler';
import { Divider,Input} from 'react-native-elements';
import axios from 'axios';
import { connect } from 'react-redux';
import { signupUser} from '../../store/actions/Section/actions';
class Signin extends Component {
state = {
fullName:'',
userName:'',
email:'',
password:'',
confirmPassword:'',
bornDate:'',
State:'',
City:''
};
handleEmailChange = val => {
this.setState({ email:val });
};
handlePasswordChange = val => {
this.setState({ password:val });
};
handleConfirmPasswordChange = val => {
this.setState({ confirmPassword:val });
};
handleNameChange = val => {
this.setState({ fullName:val });
};
handleUserNameChange = val => {
this.setState({ userName:val });
};
handleStateChange = val => {
this.setState({ State:val });
};
handleCityChange = val => {
this.setState({ City:val });
};
handleBornDateChange = val => {
this.setState({ bornDate:val });
};
onSignInUser = () => {
const {email,password} = this.state
if(email=='' || password=='')
return;
this.props.signUp(this.state.fullName,this.state.userName, this.state.email,this.state.password,this.state.confirmPassword,this.state.bornDate,this.state.State,this.state.City);
// this.props.navigation.navigate('User');
};
componentDidUpdate() {
const { idUser, loading,error } = this.props;
console.log(idUser);
console.log('aqui');
if (!loading && error) Alert.alert('Erro', error);
if (!loading && idUser) this.props.navigation.navigate('User');
}
render() {
return (
<View style={styles.container}>
<View style={styles.flexCenter}>
<Image source={logo} style={styles.logoImage}/>
<Text style={styles.logoText} >HomeShare</Text>
<Text style={styles.sublogoText} >SignUp</Text>
</View>
<Divider style={styles.divider} />
<View style={styles.flexButton}>
<View style={styles.inputContainer}>
<Input style={styles.textInput} onChangeText={this.handleNameChange} value={this.state.fullName} placeholder='Nome'/>
<Input style={styles.textInput} onChangeText={this.handleUserNameChange} value={this.state.userName} placeholder='User'/>
<Input style={styles.textInput} onChangeText={this.handleBornDateChange} value={this.state.bornDate} placeholder='Nascimento'/>
<Input style={styles.textInput} onChangeText={this.handleStateChange} value={this.state.State} placeholder='Estado'/>
<Input style={styles.textInput } onChangeText={this.handleCityChange} value={this.state.City} placeholder='Cidade'/>
<Input style={styles.textInput} onChangeText={this.handleEmailChange} value={this.state.email} placeholder='E-mail' keyboardType={'email-address'}/>
<Input style={styles.textInput} onChangeText={this.handlePasswordChange} value={this.state.password} placeholder='Senha' secureTextEntry={true}/>
<Input style={styles.textInput} onChangeText={this.handleConfirmPasswordChange} value={this.state.confirmPassword} placeholder='Confirme sua Senha' secureTextEntry={true}/>
</View>
<TouchableOpacity style={styles.button} activeOpacity={0.5} onPress={this.onSignInUser} >
<View>
<Text style={styles.buttonText}>SignIn</Text>
</View>
</TouchableOpacity>
<Text style={{marginTop:10}}>Ou</Text>
<TouchableOpacity style={styles.button} activeOpacity={0.5} onPress={this.signInUser}>
<View>
<Text style={styles.buttonText}>Entrar com Facebook</Text>
</View>
</TouchableOpacity>
</View>
</View>
);
}
}
const mapStateToProps = ({ section: { restoring, loading, user, error, logged, idUser } }) => ({
restoring: restoring,
loading: loading,
user: user,
error: error,
logged: logged,
idUser: idUser
});
const mapDispatchToProps = {
signUp:signupUser
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Signin);
My Action:
export const signupUser = (fullName,userName, email,password,confirmPassword,bornDate,State,City) => dispatch => { dispatch(sessionLoading());
firebaseService.auth().createUserWithEmailAndPassword(email, password).then(user => {
console.log(user);
firebaseService.auth().currentUser.getIdToken(true).then(function(idToken) {
SectionService.signIn(idToken,fullName,userName, email,password,confirmPassword,bornDate,State,City).then((response) =>{
console.log(response);
dispatch(sessionSetId(response));
}).catch(e=> {
dispatch(sessionError(e));
});
}).catch(function(error) {
dispatch(sessionError(e));
});
})
.catch(error => {
dispatch(sessionError(error.message));
});
A proposed solution is to handle the account creation in the createUser callback and to update it with other data in the cloud function. Alternatively you can set up a listener that looks for the document, which will then be created and the listener will be notified.
I personally create the user doc on the client side because I create it with some data only available on the client, but your use case will be dictate your preferred approach.

How to call the redux actions of one component in another

I'm rendering the data got from an API into the Cards, I created a CardContainers component that map the data I get from the API then use that component in another component.
CardContainers.js
import React from 'react';
import {View} from 'react-native';
import {withNavigation} from 'react-navigation';
class CardContainers extends React.Component{
addPlace(){
return this.props.addPlace;
}
renderCards(){
return this.props.data.map((item, index) => {
return (
<View key={index}>
{this.props.renderCard(item)}
</View>
)
})
}
render(){
return(
<View>{this.renderCards()}</View>
)
}
}
PlacesList.js
import React from 'react';
import ProgressiveInput from 'react-native-progressive-input';
import {StyleSheet, View, Alert, Text, TouchableOpacity, ListView, ScrollView} from 'react-native';
import {Button, Card, Icon} from 'react-native-elements';
import {connect} from 'react-redux';
import CardContainers from './CardContainers';
import * as placesActions from '../redux/actions/placesActions';
const ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2,
});
class PlacesList extends React.Component{
static navigationOptions = ({navigation}) => {
return {
title:'Finding new places',
}
}
constructor(props){
super(props)
const position = this.props.navigation.getParam('position')
const tripId = JSON.stringify(this.props.navigation.getParam('tripId')).replace(/\"/g,"");
const date = JSON.stringify(this.props.navigation.getParam('date')).replace(/\"/g,"");
this.state={
position: position,
tripId: tripId,
date: date,
dataSource:ds.cloneWithRows([]),
}
}
renderCard(item){
return(
<Card
key={item.id}
title={item.title}
titleStyle={styles.title}
containerStyle={{marginTop: 20, marginBottom:20}}
>
<View style={{flexDirection: 'row'}}>
<Text style={{margin:10}}>
Category: {item.category.title}
</Text>
<Text style={{margin:10}}>
Rating: {item.averageRating}
</Text>
</View>
<View style ={{flexDirection:'row', alignItems:'center', alignSelf:'center'}}>
<Button
icon={<Icon name='add' color='#ffffff'/>}
buttonStyle={{marginLeft:15, borderRadius:10}}
title='ADD THIS PLACE'
type='solid'
onPress={()=>this.props.addPlace()}
/>
</View>
</Card>
);
}
getPlacesAroundDestination = () => {
this.props.aroundPlaces(this.state.position);
this.setState({dataSource: ds.cloneWithRows(this.props.placesAround)})
}
autoComplete = async(query) => {
this.setState({destination: query})
await this.props.suggestPlaces(this.state.position, query)
this.setState({dataSource: ds.cloneWithRows(this.props.searchSuggests)})
}
inputCleared = () => {
this.setState({
destination:'',
isLoading: false,
dataSource: ds.cloneWithRows({}),
});
}
onListItemClicked = (searchSuggests) => {
this.setState({
title: searchSuggests.title,
placeId: searchSuggests.id,
openingHours: searchSuggests.openingHours,
category: searchSuggests.category,
position:searchSuggests.position.toString(),
dataSource:ds.cloneWithRows([]),
})
}
renderRow = (searchSuggests) => {
return(
<TouchableOpacity
style={{padding:10}}
onPress={()=>this.onListItemClicked(searchSuggests)}
>
<Text style={{fontSize:20}}>{searchSuggests.title}</Text>
<Text style={{fontSize:10}}>{searchSuggests.vicinity}</Text>
</TouchableOpacity>
)
}
renderSeparator = () => {
return <View style={{borderWidth:0.5, borderColor:'lightgrey',}}> </View>
}
renderContent(){
return (
<CardContainers
data={this.props.placesAround.items}
renderCard={this.renderCard}
/>
)
}
render(){
return(
<View style={styles.container}>
<ProgressiveInput
style={{marginTop:20, marginLeft:10, marginRight:10}}
placeholder='Your destination...'
value={this.state.destination}
isLoading={this.props.isLoading}
onChangeText={this.autoComplete}
onInputCleared={this.inputCleared}
/>
<View style={{flex:0}}>
<ListView
enableEmptySections
style={{backgroundColor:'white', margin:20}}
dataSource={this.state.dataSource}
renderRow={this.renderRow}
renderSeparator={this.renderSeparator}
/>
</View>
<Button
title= 'SUGGEST'
style={{alignSelf:'center'}}
onPress={() => this.props.aroundPlaces(this.state.position)}
/>
<ScrollView>
{this.props.placesAround.items? this.renderContent():null}
</ScrollView>
</View>
)
}
}
const mapStateToProps = (state) => {
return{
searchSuggests: state.places.searchSuggests,
isLoading: state.places.isLoading,
placesAround: state.places.placesAround,
geolo: state.location.latitude + ',' + state.location.longitude,
}
}
const mapDispatchToProps = (dispatch) => {
return {
addPlace:(tripId, date, title, category, rating, placeID) => dispatch (placesOfPlanActions.addPlace(tripId, date, title, category, rating, placeID)),
aroundPlaces: (geolo) => dispatch(placesActions.aroundPlaces(geolo)),
suggestPlaces: (geolo, destination) => dispatch(placesActions.suggestPlaces(geolo, destination))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(PlacesList);
As you can see in the code below, I want to call the addPlace() function which is a redux action in the onPress event of each Card rendered, but I cannot do it because the CardContainers does not have that function inside. So is there any way that I can do it? I'm quite new to react-native and redux, just spent 4 months on this and I do not think that I fully understand it.
Yup, simply add the connect HOC to CardContainers and you should be able to set the function in mapDispatchToProps like you did in PlacesList.

react-native redux can't access and update data

App.js
import React, { Component } from 'react';
import UserApp from './MainApplication';
import store from './store/index';
import { Provider } from 'react-redux';
class App extends Component {
render() {
return (
<Provider store={store}>
<UserApp />
</Provider>
);
}
}
reducer:
import { ADD_USER } from '../actions/actionTypes';
// import { initialState } from '../store/initialState';
const initialState = {
id: 0,
username: 'test',
// email: '',
// password: '',
// otp: false,
// otpColor: 'red',
// otpStatus: 'Send OTP',
};
const addUser = (state = initialState, action) => {
switch (action.type) {
case ADD_USER:
return Object.assign({}, state, {
//id: action.payload.id,
username: action.data,
// email: action.email,
// password: action.password,
// otp: action.otp,
// otpColor: action.otpColor,
// otpStatus: action.otpStatus,
});
}
return state;
};
export default addUser;
export default App;
actionCreator:
import { ADD_USER, ADD_IMAGE, UPDATE_API, SEND_OTP } from './actionTypes';
let nextID = 0;
export const addUser = (data) => ({
type: ADD_USER,
id: (nextID += 1),
data,
});
component:
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
TouchableOpacity,
Image,
Button,
TextInput,
} from 'react-native';
import { ImagePicker, Permissions } from 'expo';
// import Icon from 'react-native-vector-icons/Ionicons';
import { connect } from 'react-redux';
class Users extends Component<Props> {
constructor(props) {
super(props);
this.state = {
image: null,
};
}
_pickImage = async () => {
const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
if (status === 'granted') {
let result = await ImagePicker.launchImageLibraryAsync({
allowsEditing: true,
aspect: [4, 3],
});
console.log(result);
if (!result.cancelled) {
this.setState({ image: result.uri });
}
} else {
throw new Error('Camera roll permission not granted');
}
};
render() {
//const { fullName, email, password } = this.props.navigation.state.params;
let { image } = this.state;
return (
<View style={styles.mainContainer}>
<View styles={styles.container}>
<TouchableOpacity style={styles.imageContainer}>
image &&
<Image source={{ uri: image }} style={styles.image} />
</TouchableOpacity>
<Button
title={
this.state.image === null
? 'Pick an image from camera roll'
: 'Change Image'
}
onPress={this._pickImage}
/>
<View>
<Text style={styles.label}>Full Name: </Text>{' '}
<TextInput
placeholder={this.props.username}
//onChangeText={email => this.setState({ email })}
style={styles.input}
returnKeyType="next"
autoCapitalize="none"
autoCorrect={false}
/>
<Text style={styles.label}>Email: </Text>
<TextInput
placeholder={this.props.email}
//onChangeText={email => this.setState({ email })}
style={styles.input}
returnKeyType="next"
autoCapitalize="none"
autoCorrect={false}
/>
</View>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('Home')}
style={styles.btnContainer}>
<Text style={styles.btn}>FINISH</Text>
</TouchableOpacity>
</View>
<View>
<Text>username: {this.props.username}</Text>
</View>
</View>
);
}
}
const mapStateToProps = state => ({
username: state.username
});
export default connect(mapStateToProps)(Users);
desired Component:
import React, { Component } from 'react';
import {
View,
StyleSheet,
Text,
TextInput,
KeyboardAvoidingView,
TouchableOpacity,
ScrollView,
} from 'react-native';
import { connect } from 'react-redux';
// import { addUser } from '../reducers/addUser';
import { addUser } from '../actions';
import { ADD_USER } from '../actions/actionTypes';
class SignUp extends Component<Props> {
constructor(props) {
super(props);
// local state..
this.state = {
username: '',
email: '',
password: '',
otp: false,
otpColor: 'red',
otpStatus: 'Send OTP',
};
}
// addUser = (username) => {
// this.props.dispatch({ type: ADD_USER, username })
// }
render() {
//const { navigate } = this.props.navigation;
//const newUser = this.state;
return (
<View style={styles.mainContainer}>
<View style={styles.header}>
<View style={styles.createAccountContainer}>
<Text style={styles.createAccount}> Create an account </Text>
<View style={styles.underLineRight} />
</View>
<View style={styles.singInContainer}>
{' '}
<TouchableOpacity
onPress={() => this.props.navigation.navigate('Login')}>
<Text style={styles.signupHeader}> Sign In </Text>
</TouchableOpacity>
<View style={styles.underLineLeft} />
</View>
</View>
<View style={styles.content}>
<TextInput
placeholder="FULL NAME"
value={this.state.username}
onChangeText={username => this.setState({ username })}
// onSubmitEditing={() => this.newUser.email.focus()}
style={styles.input}
returnKeyType="next"
autoCapitalize="none"
autoCorrect={false}
/>
<View style={styles.emailContainer}>
<TextInput
placeholder="EMAIL"
value={this.state.email}
onChangeText={email => this.setState({ email })}
//onSubmitEditing={() => this.newUser.password.focus()}
keyboardType="email-address"
style={[styles.input, { flex: 2 }]}
returnKeyType="next"
autoCapitalize="none"
autoCorrect={false}
/>
<TouchableOpacity
value={this.state.email}
onPress={() => {
this.setState({
otp: true,
otpStatus: 'OTP Send',
otpColor: 'green',
});
}}
style={styles.otpInput}>
<Text style={{ color: this.state.otpColor }}>
{this.props.otpStatus}
</Text>
</TouchableOpacity>
</View>
<TextInput
placeholder="PASSWORD"
value={this.state.password}
//onChangeText={password => this.setState({ password })}
style={styles.input}
secureTextEntry={true}
returnKeyType="go"
/>
<TouchableOpacity
onPress={() => {
console.log(
this.props.username + 'removeID TouchableOpacity(104)-- Users.js'
);
if (this.props.addNewUser()) this.props.navigation.navigate('Users');
}}
// onPress={() =>
// navigate('Users', {
// username: username,
// email: email,
// password: password,
// })
// }
style={styles.btnContainer}>
<Text style={styles.btn}>Sign up</Text>
</TouchableOpacity>
</View>
<View style={styles.orContainer}>
<Text style={{ color: 'grey' }}>─────</Text>
<Text style={styles.or}>Or</Text>
<Text style={{ color: 'grey' }}>─────</Text>
</View>
<View style={styles.footer}>
<TouchableOpacity style={styles.labelsGoogle}>
<Text style={styles.btn}>google</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.labelfacebook}>
<Text style={styles.btn}>facebook</Text>
</TouchableOpacity>
</View>
<View>
<Text>username: {this.props.username}</Text>
</View>
</View>
);
}
}
// Add to the props of this class..
const mapStateToProps = state => {
console.log(state);
return {
username: state.username,
// email: state.email,
// otp: state.otp,
// otpColor: state.otpColor,
// otpStatus: state.otpStatus,
};
};
// Add to the props of this class..
const mapDispatchToProps = (dispatch) => ({
addNewUser: username => dispatch(addUser(username)),
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(SignUp);
problems are,
cannot map my initial state to the component.
not able to update the state.
i don't have a senior to ask and i'm a beginner. done a lot of surfing. the proj was working properly till converted to redux. require help. thanks in advance..
First of all, You can call action method in componenet and
import { addUser } from '../actions'; // import
this.props.addUser(); // call method
export default connect(mapStateToProps, { addUser })(Users); // connect actions method
Than you can set the reducers file in bellow
export default (state = initialState, action) => {
switch (action.type) {
case ADD_USER:
return Object.assign({}, state, {
//id: action.payload.id,
username: action.data,
// email: action.email,
// password: action.password,
// otp: action.otp,
// otpColor: action.otpColor,
// otpStatus: action.otpStatus,
});
default:
return state;
}
};

How do I disable touchableOpacity?

I am making an appointment app, I have 6 time slots on a given day. The selected slots are stored into a const called "notAvailableSlots" as soon as the component loads. How do I disable the touchableOpacity if "notAvailableSlots" has corresponding values in it, meaning someone has clicked one of the 6 slots already? I know it takes a boolean, but stuck thinking what value to pass...
const availableHours = {
timeSlots: {
slot1: "2:00pm to 2:30pm",
slot2: "2:30pm to 3:00pm",
slot3: "3:00pm to 3:30pm",
slot4: "3:30pm to 4:00pm",
slot5: "4:00pm to 4:30pm",
slot6: "4:30pm to 5:00pm"
}
};
class Appointment extends Component {
constructor(props) {
super(props);
this.state = {
datePicker: false,
date: new Date()
};
}
componentDidMount() {
this.props.fetchDataFromHeroku();
}
render() {
const availability = availableHours.timeSlots;
const notAvailableSlots = this.props.date
.filter(date => {
const month = new Date(date.date).getMonth();
const day = new Date(date.date).getDate();
const year = new Date(date.date).getFullYear();
return (
month === this.state.date.getMonth() &&
day === this.state.date.getDate() &&
year === this.state.date.getFullYear()
);
})
.map(date => date.time_slot);
// console.log(this.state.date);
console.log("not available: ", notAvailableSlots);
return (
<View style={styles.container}>
<Text style={{ backgroundColor: "#00CED1", height: 35 }}>
Hi! Please click on "calendar" to setup an appointment
</Text>
<View>
<Button
style={styles.buttonOne}
title="Make an appointment"
onPress={() => {
const { action, year, month, day } = DatePickerAndroid.open({
date: new Date()
}).then(response => {
this.setState({
datePicker: true,
date: new Date(response.year, response.month, response.day)
});
response.month += 1;
console.log("date", response);
});
}}
/>
{this.state.datePicker
? Object.keys(availability).map((time, i) => {
// console.log(time); this returns slots 1 thru 6
return (
<View key={i} style={styles.slotButton}>
<TouchableOpacity
disabled={true}
onPress={() =>
this.props.addTimeSlotToDatabase(
time,
this.props.user.id,
this.state.date
)
}
>
<Text style={{ alignItems: "center" }}>
{availability[time]}
</Text>
</TouchableOpacity>
</View>
);
})
: null}
</View>
</View>
);
}
}
Simply put the value in the state.
constructor(props) {
super(props);
this.state = {
disabled: false
};
}
render() {
return(
<TouchableOpacity disabled={this.state.disabled}>
<Text>Click</Text>
</TouchableOpacity>
)
}
Sometimes I do like this
import { TouchableOpacity, View } from 'react-native';
const MainView = isDisabled ? View : TouchableOpacity;
return (
<MainView onPress={}>