React Native : Styling DatePickerIOS component - react-native

I have a component Logitem.js which has a DatePickerIOS component.
The component works as expected but for some reason the datepicker component's layout is messed up as shown below.
Ideally the datepicker component should be on top followed by the two buttons (with adequate space between datepicker component and the buttons)
Logitem.js code
import React, { Component } from 'react';
import { Text, View, Modal, DatePickerIOS, TextInput, TouchableHighlight } from 'react-native';
export default class Logitem extends Component {
state = {
//selecteddate: '1',
selectedweight: this.props.weight,
showmodal: false,
selecteddate: new Date(86400000 * this.props.logdate),
}
componentDidMount() {
console.log('State ==> '+this.state.selecteddate+' Logstring date ==> '+this.props.logstringdate);
}
deleteSelectedRecord(){
this.setState({ showmodal: false });
this.props.invokedelete(this.state.selecteddate);
}
saveSelectedRecord(){
this.setState({ showmodal: false });
this.props.invokesave(this.state.selecteddate, this.state.selectedweight);
}
onWeightClick = () => {
this.setState({ showmodal: true }, () => {
});
}
onDateChange(date) {
this.setState({
selecteddate: date
});
}
render() {
return (
<View style={styles.containerStyle}>
<Modal
animationType="slide"
transparent={false}
visible={this.state.showmodal}
onRequestClose={() => { alert("Modal has been closed.") }}
>
<View style={{ marginTop: 22 }}>
<DatePickerIOS
date={this.state.selecteddate}
mode="date"
onDateChange={(date) => this.onDateChange(date)}
style={{ height: 100, width: 300 }}
/>
</View>
<View style={{ marginTop: 22, borderColor: '#ddd', borderWidth: 5 }}>
<TextInput
returnKeyType="done"
keyboardType='numeric'
style={{
height: 40,
width: 60,
borderColor: 'gray',
borderWidth: 1,
}}
onChangeText={(text) => this.setState({ selectedweight: text })}
value={this.state.selectedweight.toString()}
/>
<Text>KG</Text>
<TouchableHighlight style={styles.buttonstyle} onPress={this.deleteSelectedRecord.bind(this)}>
<Text style={styles.buttontextstyle}>Delete</Text>
</TouchableHighlight>
<TouchableHighlight style={styles.buttonstyle} onPress={this.saveSelectedRecord.bind(this)}>
<Text style={styles.buttontextstyle}>Save</Text>
</TouchableHighlight>
</View>
</Modal>
<View style={styles.headerContentStyle}>
<Text>{this.props.logstringdate}</Text>
<Text>{this.props.bmi}</Text>
</View>
<View style={styles.thumbnailContainerStyle}>
<Text onPress={this.onWeightClick}>{this.props.weight}</Text>
</View>
</View>
);
}
};
const styles = {
containerStyle: {
borderWidth: 1,
borderRadius: 2,
borderColor: '#ddd',
borderBottomWidth: 1,
//shadowColor: '#000',
//shadowOffset: { width: 0, height: 2},
//shadowOpacity: 0.1,
//shadowRadius: 2,
//elevation: 1,
marginLeft: 5,
marginRight: 5,
marginTop:10,
},
thumbnailContainerStyle: {
justifyContent: 'center',
alignItems: 'center',
marginLeft: 10,
marginRight: 10,
flexDirection: 'row'
},
headerContentStyle: {
flexDirection: 'column',
justifyContent: 'space-around'
},
buttonstyle: {
marginRight: 40,
marginLeft: 40,
marginTop: 10,
paddingTop: 20,
paddingBottom: 20,
backgroundColor: '#68a0cf',
borderRadius: 10,
borderWidth: 1,
borderColor: '#fff'
},
buttontextstyle: {
color: '#fff',
textAlign: 'center',
}
};

Related

how to validate DateTimePickerModal with yup and formik in React native?

Here is my screen component with two textinputs from the link. I have removed some other code that isn't necessary to this issue.
When i choose the date from the popup it appears in the text input but doesnt get validated.
I cannot use the result of DatePicker component as it is , so i am doing some formating and saved to a function getDate.
How would you go about implemnting this ? is there any better way
enter image description here
import React, { useState, useContext, useEffect } from 'react';
import {
StyleSheet,
View,
Text,
TextInput,
TouchableOpacity,
ScrollView,
KeyboardAvoidingView,
Platform,
Image,
} from 'react-native';
import { icons, COLORS, } from '../constants';
import { Formik } from 'formik';
import * as yup from "yup";
import client from '../api/client';
import DateTimePickerModal from "react-native-modal-datetime-picker";
const addfarm = ({ navigation, Arrival_Date }) => {
const addFarmValidationSchema = yup.object().shape({
Farm_Code: yup.string().required('Please Enter the chick price'),
Arrival_Date: yup.string().required('Please Choose a date'),
});
const [isDatePickerVisible, setDatePickerVisibility] = useState(false);
const [date, setDate] = useState('');
const showDatePicker = () => {
setDatePickerVisibility(true);
};
const hideDatePicker = () => {
setDatePickerVisibility(false);
};
const handleConfirm = (date) => {
hideDatePicker();
setDate(date);
};
const getDate = () => {
let tempDate = JSON.stringify(date).split(/[ ",T,]/);
return date !== ''
? `${tempDate[1]}`
: '';
};
const newDate = getDate();
const addFarmInfo = {
Farm_Code: '',
Arrival_Date: '',
};
const add = async (values) => {
const res = await client({
method: 'POST',
url: '/Farm/SaveFarm',
data: JSON.stringify({ ...values, id })
})
.then(res => console.log(res.data))
.catch(err => console.log(err))
}
return (
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : null}
style={{ flex: 1 }}>
<ScrollView style={styles.container}>
<Formik
initialValues={addFarmInfo}
validateOnMount={true}
onSubmit={add}
validationSchema={addFarmValidationSchema}>
{({
handleChange,
handleBlur,
handleSubmit,
values,
touched,
errors,
isValid,
setFieldValue,
}) => {
const {
Farm_Code,
Arrival_Date,
} = values
return (
<View
style={{
paddingHorizontal: '10%',
paddingTop: 50,
marginTop: 50,
backgroundColor: COLORS.main_background,
}}>
<Text style={styles.auth_text}>Add Farm</Text>
<Text style={styles.tag}>
Farm Code:
</Text>
<View
style={[styles.textInputView, { marginBottom: 10 }]}>
<TextInput
onChangeText={handleChange('Farm_Code')}
onBlur={handleBlur('Farm_Code')}
value={Farm_Code}
placeholder="Farm Code"
placeholderTextColor={COLORS.placeholder_fonts}
selectionColor={COLORS.drawer_button}
style={styles.textInput}
/>
<Image
source={!errors.Farm_Code ? icons.tick : icons.close}
resizeMode="stretch"
style={{
width: 18,
height: 18,
tintColor: !errors.Farm_Code ? COLORS.drawer_button : 'red',
alignItems: 'center',
marginRight: 10,
}}
/>
</View>
{(errors.Farm_Code && touched.Farm_Code) &&
<Text style={styles.errors}>{errors.Farm_Code}</Text>
}
<Text style={styles.tag}>
Arrival Date:
</Text>
<View
style={[styles.textInputView, { marginBottom: 10 }]}>
<TextInput
onChangeText={handleChange('Arrival_Date')}
onBlur={handleBlur('Arrival_Date')}
value={newDate}
onFocus={showDatePicker}
placeholder="yyyy/mm/dd"
placeholderTextColor={COLORS.placeholder_fonts}
selectionColor={COLORS.drawer_button}
style={styles.textInput}
/>
<TouchableOpacity style={{ marginRight: 10, }}
onPress={showDatePicker}
>
<DateTimePickerModal
isVisible={isDatePickerVisible}
mode="date"
onConfirm={handleConfirm}
onCancel={hideDatePicker}
/>
<Image
source={icons.calendar}
resizeMode="stretch"
style={{
width: 18,
height: 18,
tintColor: COLORS.secondary_fonts,
alignItems: 'center'
}}
/>
</TouchableOpacity>
<Image
source={!errors.Arrival_Date ? icons.tick : icons.close}
resizeMode="stretch"
style={{
width: 18,
height: 18,
tintColor: !errors.Arrival_Date ? COLORS.drawer_button : 'red',
alignItems: 'center',
marginRight: 10,
}}
/>
</View>
{(errors.Arrival_Date && touched.Arrival_Date) &&
<Text style={styles.errors}>{errors.Arrival_Date}</Text>
}
{(errors.Arrival_Date && touched.Arrival_Date) &&
<Text style={styles.errors}>{errors.Arrival_Date}</Text>
}
{/* Save */}
<TouchableOpacity
disabled={!isValid}
onPress={handleSubmit}
style={[styles.button, { backgroundColor: isValid ? COLORS.authButtons : COLORS.placeholder_fonts, marginTop: 10 }]}>
<Text style={styles.button_Text}>Save</Text>
</TouchableOpacity>
</View>
)
}
}
</Formik >
</ScrollView>
</KeyboardAvoidingView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: COLORS.main_background,
},
textInput: {
flex: 1,
paddingLeft: 10,
color: 'black',
},
auth_text: {
fontSize: 20,
fontWeight: 'bold',
textAlign: 'center',
marginBottom: 5,
},
button: {
height: 50,
width: '100%',
marginVertical: 20,
borderRadius: 10,
alignItems: 'center',
justifyContent: 'center',
},
button_Text: {
fontSize: 18,
color: COLORS.white,
},
login_nav: {
fontSize: 12,
textAlign: 'center',
fontWeight: '400',
marginTop: 10,
},
errors: {
fontSize: 14,
color: 'red',
fontWeight: '400',
marginTop: 5,
},
textInputView: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
borderWidth: 1,
borderRadius: 10,
height: 50,
width: '100%',
borderColor: COLORS.secondary_fonts,
},
tag: {
color: 'black',
fontSize: 15,
marginBottom: 4,
marginLeft: 4
},
});
export default addfarm;
If you want formik to handle the validation, you should call the setFieldValue method and it will trigger the validation as the documentation says

I am trying to implement text change and edit ends in TextInput using react-native but it's not quite working. Can any one help me?

I am trying to implement text change and edit ends in TextInput using react-native but it's not quite working.
See the Screenshot Here
Currently, when changing the price by touch input, the price is not affected when click off.
Here are my files
CartItem.js:
import React from "react";
import {
View,
TextInput,
Image,
TouchableOpacity,
StyleSheet,
Platform,
Alert,
} from "react-native";
//Colors
import Colors from "../../../utils/Colors";
//NumberFormat
import NumberFormat from "../../../components/UI/NumberFormat";
//Icon
import { MaterialCommunityIcons } from "#expo/vector-icons";
import CustomText from "../../../components/UI/CustomText";
//PropTypes check
import PropTypes from "prop-types";
export class CartItem extends React.PureComponent {
render() {
const { item, onAdd, onDes, onRemove } = this.props;
const AddItemHandler = async () => {
await onAdd();
};
const sum = +item.item.price * +item.quantity;
const checkDesQuantity = async () => {
if (item.quantity == 1) {
Alert.alert(
"Clear cart",
"Are you sure you want to remove the product from the cart?",
[
{
text: "Cancel",
},
{
text: "Yes",
onPress: onRemove,
},
]
);
} else {
await onDes();
}
};
return (
<View style={styles.container}>
<View style={styles.left}>
<Image
style={{
width: "100%",
height: 90,
resizeMode: "stretch",
borderRadius: 5,
}}
source={{ uri: item.item.thumb }}
/>
</View>
<View style={styles.right}>
<View
style={{ flexDirection: "row", justifyContent: "space-between" }}
>
<CustomText style={styles.title}>{item.item.filename}</CustomText>
<View>
<TouchableOpacity onPress={onRemove}>
<MaterialCommunityIcons name='close' size={20} color='#000' />
</TouchableOpacity>
</View>
</View>
<CustomText style={{ color: Colors.grey, fontSize: 12 }}>
Provided by Brinique Livestock LTD
</CustomText>
<NumberFormat price={sum.toString()} />
<View style={styles.box}>
<TouchableOpacity onPress={checkDesQuantity} style={styles.boxMin}>
<MaterialCommunityIcons name='minus' size={16} />
</TouchableOpacity>
Code that I would like to be fixed starts here.
<View>
<TextInput
keyboardType='numeric'
onEndEditing={AddItemHandler}
style={styles.boxText}>{item.quantity}</TextInput>
</View>
Code that I would like to be fixed ends here.
<TouchableOpacity
onPress={AddItemHandler}
style={styles.boxMin}>
<MaterialCommunityIcons name='plus' size={16} />
</TouchableOpacity>
</View>
</View>
</View>
);
}
}
CartItem.propTypes = {
item: PropTypes.object.isRequired,
onAdd: PropTypes.func.isRequired,
onRemove: PropTypes.func.isRequired,
onDes: PropTypes.func.isRequired,
};
const styles = StyleSheet.create({
container: {
flex: 1,
marginHorizontal: 10,
height: 110,
borderBottomWidth: 1,
borderBottomColor: Colors.light_grey,
flexDirection: "row",
paddingVertical: 10,
alignItems: "center",
backgroundColor: "#fff",
paddingHorizontal: 10,
borderRadius: 5,
marginTop: 5,
},
left: {
width: "35%",
height: "100%",
alignItems: "center",
},
right: {
width: "65%",
paddingLeft: 15,
height: 90,
// overflow: "hidden",
},
title: {
fontSize: 14,
},
box: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
height: Platform.OS === "ios" ? 30 : 25,
backgroundColor: Colors.grey,
width: 130,
borderRadius: 5,
paddingHorizontal: 15,
marginTop: 5,
},
boxMin: {
width: "30%",
alignItems: "center",
},
boxText: {
fontSize: 16,
backgroundColor: Colors.white,
padding: 5,
},
});
Use onBlur instead of onEndEditing.
How should the input end triggered?
After a time?
When user hits enter?
When user taps anywhere to close software keyboard?
Instead of
onEndEditing={AddItemHandler}
Use:
onBlur={(e) => {AddItemHandler(e.nativeEvent.text)}}
And ensure that AddItemHandler can handle the value in e.nativeEvent.text.

React Native close Modal that is opened by different component

Hello I am fairly new to React Native and am currently having an issue with my modal component. My modal component has two props, gameData and isModalVisible. In Home.js modal prop isModalVisible has the value of a state variable isVisible that gets changed to true when a certain TouchableOpacity is pressed. Then inside my FeaturedGameModal.js isModalVisible is set from props. The issue I am having is closing the modal. Opening the modal this way works fine, but how should I close the modal since its visibility is being controlled by props that are in Home.js? Any help would be greatly appreciated. I have been working on this for two days now and it is driving me crazy. Thanks! I will include my two files in case you want to more closely inspect my code.
Home.js:
import React from 'react';
import {
View,
Text,
Image,
SafeAreaView,
TouchableOpacity,
ActivityIndicator,
Linking,
ScrollView,
TouchableHighlight,
} from 'react-native';
import {homeStyles} from '../styles/homeStyles';
import {styles} from '../styles/styles';
import {createIconSetFromIcoMoon} from 'react-native-vector-icons';
import icoMoonConfig from '../../assets/fonts/selection.json';
import {fetchData} from '../functions/fetch';
import Modalz from '../modals/FeaturedGameModal';
const Icon = createIconSetFromIcoMoon(icoMoonConfig);
class Home extends React.Component {
myData = {};
constructor(props) {
super(props);
this.state = {
error: false,
isFetching: true,
featuredGameModal: false,
isVisible: false,
};
}
handleFeaturedGame = async () => {
this.setState({}, async () => {
try {
const featureGameData = await fetchData(
'http://dev.liberty.edu/templates/flames/json/json_appHomeFeed.cfm',
);
this.setState({
error: false,
featuredGameData: featureGameData,
isFetching: false,
});
} catch (e) {
this.setState({
error: true,
});
console.log(e.message);
}
});
};
handleFeaturedModal() {
this.setState({featuredGameModal: false});
}
componentDidMount() {
this.handleFeaturedGame();
}
render() {
const {featuredGameData} = this.state;
return this.state.isFetching ? (
<View style={styles.center}>
<ActivityIndicator size="large" color="#AE0023" />
</View>
) : (
<ScrollView>
<SafeAreaView>
<View style={homeStyles.featuredGameContainer}>
<View style={homeStyles.centerHor}>
<Image
style={homeStyles.logo}
source={require('../../assets/images/FlamesLogo.png')}
/>
</View>
<View style={homeStyles.gameTimeContainer}>
<Text style={homeStyles.gameTime}>
{featuredGameData.featuredGame.eventdate}
</Text>
<Text style={homeStyles.gameTime}>
{featuredGameData.featuredGame.eventtime}
</Text>
</View>
<TouchableOpacity
activeOpacity={0.6}
onPress={() => {
this.setState({isVisible: true});
}}>
<View style={homeStyles.contentContainer}>
<View style={homeStyles.contentLeft}>
<Text style={homeStyles.teamText}>
{featuredGameData.featuredGame.teamname}
</Text>
<Text style={homeStyles.opponentText}>
vs {featuredGameData.featuredGame.opponent}
</Text>
<Text style={homeStyles.locationText}>
<Icon size={12} name={'location'} />
{featuredGameData.featuredGame.location}
</Text>
</View>
<View style={homeStyles.contentRight}>
<Image
style={homeStyles.opponentLogo}
source={{
uri: featuredGameData.featuredGame.OpponentLogoFilename,
}}
/>
</View>
</View>
</TouchableOpacity>
<View style={homeStyles.allContent}>
<Modalz
gameData={this.state.featuredGameData.featuredGame}
isModalVisible={this.state.isVisible}
/>
<View style={homeStyles.contentContainerBottom}>
<View style={homeStyles.contentLeft}>
<TouchableOpacity
style={homeStyles.buyTicketBtn}
onPress={() =>
Linking.openURL(featuredGameData.featuredGame.buyTickets)
}>
<Text style={homeStyles.buyTicketBtnText}>Buy Tickets</Text>
</TouchableOpacity>
</View>
<View style={homeStyles.liveContainer}>
<Text style={homeStyles.live}>Experience Live:</Text>
<View style={homeStyles.liveIconsContainer}>
<Icon
style={{color: '#FFF', marginRight: 4}}
size={15}
name={'radio'}
/>
<Icon style={{color: '#FFF'}} size={12} name={'LFSN'} />
</View>
</View>
</View>
</View>
</View>
<View style={homeStyles.newsContainer}>
{featuredGameData.News.map((item, key) => (
<View
key={key}
style={[homeStyles.centerHor, homeStyles.newsCard]}>
<Image
style={homeStyles.newsImage}
source={{
uri: item.Thumbnail,
}}
/>
<Text style={homeStyles.headline}>{item.Headline}</Text>
<View style={homeStyles.teamNameView}>
<Text style={homeStyles.teamNameText}>{item.teamname}</Text>
<Text>{item.GameDate}</Text>
</View>
</View>
))}
</View>
</SafeAreaView>
</ScrollView>
);
}
}
export default Home;
FeaturedGameModal.js:
import React from 'react';
import {
Alert,
Modal,
StyleSheet,
Text,
TouchableHighlight,
View,
Image,
Dimensions,
TouchableOpacity,
SafeAreaView,
} from 'react-native';
import {createIconSetFromIcoMoon} from 'react-native-vector-icons';
import icoMoonConfig from '../../assets/fonts/selection';
import {homeStyles} from '../styles/homeStyles';
const Icon = createIconSetFromIcoMoon(icoMoonConfig);
const windowWidth = Dimensions.get('window').width;
export default class Modalz extends React.Component {
constructor(props) {
super(props);
this.state = {
teamName: props.gameData.teamname,
opponentName: props.gameData.opponent,
eventDate: props.gameData.eventdate,
liveAudioURL: props.gameData.LiveAudioURL,
liveStatsURL: props.gameData.LiveStatsURL,
videoURL: props.gameData.VideoURL,
opponentLogoURL: props.gameData.OpponentLogoFilename,
};
}
render() {
const {
opponentName,
teamName,
eventDate,
opponentLogoURL,
liveStatsURL,
liveAudioURL,
videoURL,
location,
} = this.state;
const {isModalVisible} = this.props;
return (
<View>
<View style={styles.centeredView}>
<Modal
animationType="slide"
transparent={true}
visible={isModalVisible}
onRequestClose={() => {
Alert.alert('Modal has been closed.');
}}>
<SafeAreaView style={{flex: 1, backgroundColor: 'transparent'}}>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Icon
style={styles.closeButton}
size={25}
name={'x'}
onPress={() => {}}
/>
<Text style={styles.upcomingGameTitle}>
{teamName} vs {opponentName}
</Text>
<Text style={styles.upcomingGameSubtitle}>{eventDate}</Text>
<View style={styles.facingLogosBlock}>
<View style={styles.leftTeamBlock} />
<View style={styles.rightTeamBlock} />
<View style={styles.vsTextWrapper}>
<Text style={styles.vsText}>VS</Text>
</View>
<View style={styles.logoWrapper}>
<Image
style={styles.facingLogoImg}
source={{
uri:
'https://www.liberty.edu/templates/flames/images/flamesMonogram.png',
}}
/>
<Image
style={styles.facingLogoImg}
source={{uri: opponentLogoURL}}
/>
</View>
</View>
<View>
<TouchableOpacity style={styles.buyTicketBtn}>
<Text style={styles.buyTicketBtnText}>Buy Tickets</Text>
</TouchableOpacity>
</View>
<View style={styles.buttonRow}>
<TouchableOpacity
style={{...styles.iconButton, ...styles.iconButtonLeft}}>
<Icon
style={styles.iconButtonIcon}
size={25}
name={'flag'}
onPress={() => {
this.toggleModal(!this.state.modalVisible);
}}
/>
<Text style={styles.iconButtonText}>Game Day</Text>
</TouchableOpacity>
<TouchableOpacity
style={{...styles.iconButton, ...styles.iconButtonRight}}>
<Icon
style={styles.iconButtonIcon}
size={25}
name={'stats'}
onPress={() => {
this.toggleModal(!this.state.modalVisible);
}}
/>
<Text style={styles.iconButtonText}>Live Stats</Text>
</TouchableOpacity>
</View>
<View style={styles.liveLinkBlock}>
<View style={styles.liveLinkLeft}>
<Icon
style={styles.iconButtonIcon}
size={18}
name={'LFSN'}
/>
<Text>The Journey 88.3 FM</Text>
</View>
<TouchableOpacity style={styles.liveButton}>
<Text style={styles.liveButtonText}>Listen Live</Text>
</TouchableOpacity>
</View>
<View style={styles.liveLinkBlock}>
<View style={styles.liveLinkLeft}>
<Icon
style={styles.iconButtonIcon}
size={18}
name={'espn3'}
/>
<Text>LFSN TV Production</Text>
</View>
<TouchableOpacity style={styles.liveButton}>
<Text style={styles.liveButtonText}>Watch Live</Text>
</TouchableOpacity>
</View>
</View>
</View>
</SafeAreaView>
</Modal>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
centeredView: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
modalView: {
flex: 1,
alignSelf: 'stretch',
backgroundColor: 'white',
borderTopLeftRadius: 20,
borderTopRightRadius: 20,
paddingTop: 14,
alignItems: 'center',
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5,
},
openButton: {
backgroundColor: '#F194FF',
borderRadius: 20,
padding: 10,
elevation: 2,
},
closeButton: {
position: 'absolute',
right: 16,
top: 16,
color: '#000',
},
closeText: {
color: '#000',
fontWeight: 'bold',
textAlign: 'center',
fontSize: 20,
},
upcomingGameTitle: {
color: '#19191A',
fontSize: 18,
fontWeight: 'bold',
},
upcomingGameSubtitle: {
color: '#747676',
fontSize: 13,
fontWeight: 'bold',
marginBottom: 16,
},
modalText: {
marginBottom: 15,
textAlign: 'center',
},
facingLogosBlock: {
flexDirection: 'row',
position: 'relative',
alignItems: 'center',
},
facingLogoImg: {
width: 100,
height: 100,
resizeMode: 'contain',
flex: 1,
},
leftTeamBlock: {
width: 0,
height: 0,
backgroundColor: 'transparent',
borderStyle: 'solid',
borderRightWidth: 35,
borderTopWidth: 185,
borderRightColor: 'transparent',
borderTopColor: '#AE0023',
borderLeftColor: '#AE0023',
borderLeftWidth: windowWidth / 2,
left: 15,
zIndex: -1,
position: 'relative',
},
rightTeamBlock: {
width: 0,
height: 0,
backgroundColor: 'transparent',
borderStyle: 'solid',
borderLeftWidth: 35,
borderBottomWidth: 185,
borderBottomColor: '#461964',
borderRightColor: '#461964',
borderLeftColor: 'transparent',
borderRightWidth: windowWidth / 2,
right: 15,
zIndex: -1,
position: 'relative',
},
vsTextWrapper: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
justifyContent: 'center',
alignItems: 'center',
},
vsText: {
color: '#000000',
backgroundColor: '#FFFFFF',
padding: 5,
fontWeight: 'bold',
},
logoWrapper: {
position: 'absolute',
width: windowWidth,
height: 185,
top: 0,
left: 35,
flexDirection: 'row',
alignItems: 'center',
},
buyTicketBtn: {
marginTop: 24,
backgroundColor: '#AE0023',
borderRadius: 4,
paddingVertical: 20,
paddingHorizontal: 12,
width: windowWidth - 24,
},
buyTicketBtnText: {
fontSize: 21,
color: '#fff',
fontWeight: 'bold',
alignSelf: 'center',
textTransform: 'uppercase',
},
buttonRow: {
paddingVertical: 24,
paddingHorizontal: 12,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
},
iconButton: {
backgroundColor: '#F0F3F5',
borderRadius: 4,
paddingVertical: 14,
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'row',
flex: 1,
},
iconButtonText: {
color: '#19191A',
fontWeight: 'bold',
fontSize: 16,
marginLeft: 10,
},
iconButtonIcon: {
color: '#000',
},
iconButtonLeft: {
marginRight: 6,
},
iconButtonRight: {
marginLeft: 6,
},
liveLinkBlock: {
padding: 12,
borderStyle: 'solid',
borderTopColor: '#F0F3F5',
borderTopWidth: 1,
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'row',
},
liveButton: {
backgroundColor: '#F0F3F5',
borderRadius: 4,
paddingVertical: 14,
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
liveButtonText: {
color: '#19191A',
fontWeight: 'bold',
fontSize: 16,
},
liveLinkLeft: {
flex: 2,
},
});
You should create hideModal function in Home.js then pass it to Modalz component.
In Home.js, add this function:
hideModalz = () => {
this.setState({isVisible: true});
}
And pass this function to Modalz props:
<Modalz
gameData={this.state.featuredGameData.featuredGame}
isModalVisible={this.state.isVisible}
hide={hideModalz}
/>
In Modalz, call this.props.hide(); if you want to hide modal.

React Native: Display FlatList data in Modal

I have a react native flat list that renders some data from a Wordpress website using wp rest api. The flat list is displaying the post correctly, and when clicked, it opens the modal, but I am having some trouble pushing the state to the modal.
Currently, when the modal opens, it shows the same (last post/item) for every item in the flat list. Any suggestions? Any help appreciated.
import React, { Component } from 'react';
import {
Image, Dimensions, View, ActivityIndicator, TouchableOpacity, TouchableHighlight,
WebView, ScrollView, StyleSheet, ImageBackground, FlatList, Text
} from 'react-native';
import Moment from 'moment';
import HTML from 'react-native-render-html';
import Modal from "react-native-modal";
export default class LatestNews extends Component {
constructor(props) {
super(props);
this.state = {
isModalVisible: false,
isLoading: true,
posts: [],
id: null,
};
}
componentDidMount() {
fetch(`http://mywebsite.com/wp-json/wp/v2/posts/?_embed&categories=113`)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
posts: responseJson,
})
})
.catch((error) => {
console.error(error);
});
}
_toggleModal = () =>
this.setState({
isModalVisible: !this.state.isModalVisible,
});
_renderItem = ({item}) => {
return (
<TouchableOpacity onPress={() => this._onPressItem(item.id)} key={item.id}>
<View>
{item._embedded['wp:featuredmedia'].filter(
element => element.id == item.featured_media
).map((subitem, index) => (
<View style={{
margin: '5%',
borderWidth: 1,
borderColor: '#d8d8d8',
borderRadius: 10,
shadowColor: '#000',
shadowOffset: { width: 0, height: 5 },
shadowOpacity: 0.2,
shadowRadius: 8,
elevation: 1,
}}>
<ImageBackground
style={styles.news}
source={{ uri: subitem.media_details.sizes.medium.source_url }}
key={item.id}>
<View style={styles.itemTitle}>
<Text style={{ fontSize: 16, fontWeight: 'bold' }}>
{item.title.rendered}
</Text>
</View>
</ImageBackground>
</View>
))}
</View>
</TouchableOpacity>
)
};
_onPressItem(id) {
this.setState({
isModalVisible: true,
id: id,
});
};
render() {
if (this.state.isLoading == true) {
return (
<View style={{ flex: 1, flexDirection: 'column', justifyContent: 'center', alignItems: 'center', }}>
<ActivityIndicator size="large" color="#1C97F7" />
</View>
)
}
else {
Moment.locale('en');
return (
<View>
{this.state.posts.map((item, index) => (
<Modal isVisible={this.state.isModalVisible} id={this.state.id}>
{item._embedded['wp:featuredmedia'].filter(
element => element.id == item.featured_media
).map((subitem, index) => (
<ScrollView style={
{ flex: 1, backgroundColor: 'white', padding: 20, paddingBottom: 40,}
}>
<ImageBackground
style={styles.news}
source={{ uri: subitem.media_details.sizes.medium.source_url }}
key={item.id} />
<TouchableOpacity onPress={this._toggleModal}>
<Text>Hide me!</Text>
</TouchableOpacity>
<HTML
tagsStyles={{
body: {fontSize: 16, paddingBottom: 20,},
p: {fontSize: 16, fontWeight: "normal", marginTop: 10, marginBottom: 20},
strong: {fontSize: 20,},
blockquote: {fontSize: 20},
a: {fontSize: 16, color: "#0044e2"},
em: {fontSize: 20,},
img: {height: 250, width: 350},
}}
key={item.id}
styleName="paper md-gutter multiline"
html={item.content.rendered}
imagesMaxWidth={Dimensions.get('window').width * .9}
ignoredStyles={['width', 'height', 'video']}
/>
</ScrollView>
))}
</Modal>
))}
<FlatList
data={this.state.posts}
renderItem={this._renderItem}
keyExtractor={(item, index) => index}
/>
</View>
)
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
paddingTop: 0,
},
h1: {
color: 'black',
fontSize: 24,
paddingTop: 20,
fontWeight: 'bold',
},
h2: {
color: 'black',
fontSize: 24,
paddingTop: 20,
fontWeight: 'bold',
},
h3: {
fontSize: 13,
},
button: {
width: '45%',
margin: 5,
backgroundColor: '#492661',
padding: 8,
height: 36,
borderRadius: 18,
},
buttonGrey: {
width: '45%',
margin: 5,
backgroundColor: '#353535',
padding: 8,
height: 36,
borderRadius: 18,
},
buttonText: {
color: 'black',
alignSelf: 'center',
},
highlight: {
backgroundColor: '#f5f5f5',
borderRadius: 50,
width: 100,
height: 100,
marginRight: 20,
alignItems: 'center',
justifyContent: 'center',
borderColor: 'gold',
borderWidth: 0,
},
news: {
backgroundColor: '#f5f5f5',
borderRadius: 10,
width: '100%',
height: 200,
overflow: 'hidden',
},
hero: {
backgroundColor: '#492661',
width: '110%',
height: 260,
alignSelf: 'center',
marginTop: 0,
overflow: 'hidden'
},
itemTitle: {
backgroundColor: 'rgba(255,255,255,0.9)',
paddingVertical: 10,
position: 'absolute',
bottom: 0,
right: 0,
width: '100%',
paddingHorizontal: 10,
},
});
In FlatList, this is the issue it can't re-render again if dataModel is being there. For this You can use this :
in FlatList there is a propsTypes: ExtraData={} in this you should add a new boolean state, and wherever you again add the data in flatlist . set the state for that boolean key , that would help you :
<FlatList
data={this.state.posts}
renderItem={this._renderItem}
keyExtractor={(item, index) => index}
extraData={this.state.extraData}
/>
where you want add flatList data again add this line:
this.setState({extraData:!this.state.extraData})
by this line render method run again , and you will find a new update records.
Use this, this help me.

How to align one component to left and other to right (end of page) react native?

I'm making an app in React Native and I want align a circle with the end of page.
I want to make this:
But it's currently like this and only stays this way:
The complete view:
[
I already tried alignSelf, justifyContent and others but it doesn't work.
I tested this: How to align 2 react native elements, 1 being in the center and 1 on the beginning
But it won't work.
My code:
const ListProductsHeader = () => (
<View>
<View style={style.containerInfo}>
<View style={style.circle} />
<View>
<Text style={style.unityName}>SUPERMERCADO MACCARTNEY</Text>
<Text style={style.subInfo}>Categoria: Mercado</Text>
<Text style={style.subInfo}>Pedido Nº: 1245</Text>
</View>
</View>
<View style={style.containerProducts}>
<Text style={style.productName}>1x 42 - Coca Cola 2L</Text>
<View style={style.minus}></View>
</View>
</View>
);
CSS:
containerProducts:{
paddingTop: 40,
paddingLeft: 15,
flexDirection: 'row',
},
productName: {
alignSelf: 'flex-start',
},
minus:{
width: 20,
height: 20,
borderRadius: 20/2,
backgroundColor: 'red',
},
containerInfo:{
paddingTop:15,
flexDirection:'row',
paddingLeft: 15,
},
unityName:{
fontWeight: 'bold',
paddingLeft: 15,
},
subInfo:{
color: 'gray',
paddingLeft: 15,
},
circle: {
width: 50,
height: 50,
borderRadius: 50/2,
backgroundColor: 'red',
justifyContent: 'flex-end',
},
Lkke to suggest one thing that can help you with this problem
what you need to do is. Everthing is correct except the main view css
<View style={flexDirection:'row',justifyContent : 'space-between'}>
<View style={style.circle} />
<View>
<Text style={style.unityName}>SUPERMERCADO MACCARTNEY</Text>
<Text style={style.subInfo}>Categoria: Mercado</Text>
<Text style={style.subInfo}>Pedido Nº: 1245</Text>
</View>
</View>
<View style={style.containerProducts}>
<Text style={style.productName}>1x 42 - Coca Cola 2L</Text>
<View style={style.minus}></View>
</View>
try this may be it can help you
containerProducts: {
paddingTop: 40,
paddingLeft: 15,
flexDirection: 'row',
justifyContent: 'space-between',
},
Fully Customisable chat in React Native
import React, {Component} from 'react';
import {
Text,
StyleSheet,
View,
TextInput,
TouchableOpacity,
SafeAreaView,
FlatList,
} from 'react-native';
export default class CustomChatScreen extends Component {
state = {
messages: [
{
msg: 'Heloo',
id: Math.random(),
token: '',
email: '',
type: 'server',
},
{
msg: 'Server Message',
id: Math.random(),
token: '',
email: '',
type: 'server',
},
],
value: '',
};
sendMessageToServer = () => {
if (this.state.value !== '') {
let payload = {
msg: this.state.value,
id: Math.random(),
token: '',
email: '',
type: 'client',
};
let mydata = this.state.messages;
mydata.push(payload);
this.setState({
messages: mydata,
value: '',
});
}
};
renderFlatListItem = rowData => {
return (
<View style={styles.flatListContainerStyle}>
{rowData.item.type === 'client' ? (
<View style={styles.clientMsgStyle}>
<Text>{rowData.item.msg}</Text>
</View>
) : (
<View style={styles.serverMsgStyle}>
<Text>{rowData.item.msg}</Text>
</View>
)}
</View>
);
};
render() {
return (
<SafeAreaView style={styles.container}>
<FlatList
data={this.state.messages}
keyExtractor={(item, index) => index.toString()}
renderItem={this.renderFlatListItem}
/>
<View style={styles.sendMessageConatinerStyle}>
<TextInput
style={styles.sendMsgTextInputStyle}
value={this.state.value}
placeholder = {"please type here!"}
placeholderTextColor = {"#000"}
onChangeText={val => this.setState({value: val})}></TextInput>
<TouchableOpacity
style={styles.sendMsgButtonStyle}
onPress={this.sendMessageToServer}>
<Text>Send Message</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
sendMessageConatinerStyle: {
width: '100%',
height: 60,
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
backgroundColor: 'white',
flexDirection: 'row',
},
sendMsgTextInputStyle: {
backgroundColor: '#e0f2f1',
flex: 0.8,
borderTopLeftRadius: 62.5,
borderBottomLeftRadius: 62.5,
padding: 20,
},
sendMsgButtonStyle: {
flex: 0.2,
backgroundColor: '#80cbc4',
borderBottomRightRadius: 62.5,
borderTopRightRadius: 62.5,
fontSize: 18,
justifyContent: 'center',
alignItems: 'center',
},
flatListContainerStyle: {
backgroundColor: '#e0f7fa',
marginTop: 10,
},
clientMsgStyle: {
backgroundColor: '#ffab91',
borderRadius: 20,
padding: 15,
alignSelf: 'flex-end',
},
serverMsgStyle: {
backgroundColor: '#4fc3f7',
borderRadius: 20,
padding: 15,
alignSelf: 'flex-start',
},
});