Issue making model pop up onPress of flatlist - react-native

I have a flatlist of cards, and I want a modal to appear when someone presses the card. Pressing the card doesn't seem to do anything though, so I'm wondering what I've done wrong. In my code at the top I have defined the state for the visibility of the modal, if you scroll down to the card you'll see onPress changes the state. Below the card is the actual modal which uses the state of the visible property to display it or not.
Code:
class HomeScreen extends React.Component {
state = {
isModalVisible: false
};
toggleModal = () => {
this.setState({ isModalVisible: !this.state.isModalVisible });
};
render() {
return (
<View style = {{flex:1}}>
<Header
centerComponent={{ text: 'MY MACROS', style: { color: '#fff', letterSpacing: 2} }}
containerStyle={{
backgroundColor: '#5BC0EB',
}}
/>
<Progress.Bar progress={0.7} width={null} height={10} borderRadius = {0} color = {'lightgreen'}/>
<ScrollView>
<FlatList
data = {Macros}
renderItem = {({ item }) => (
<TouchableOpacity>
<Card style = {{justifyContent: 'center', margin: 1, backgroundColor: '#ffff', borderRadius: 25}} onPress = {() => {this.toggleModal}}>
<Card.Content>
<View style = {{flexDirection: 'row', justifyContent: 'space-between'}}>
<View style = {{flexDirection: 'column', justifyContent: 'space-between'}}>
<Title style = {{paddingTop: 20, fontSize: 35, fontWeight: 'bold',color: 'black', letterSpacing: 2}}>{item.total} {item.unit}</Title>
<Text style= {{fontSize: 30, color: 'black', letterSpacing: 2, fontWeight: '100'}}>{item.title}</Text>
</View>
<MainProgress/>
</View>
</Card.Content>
<Card.Actions>
</Card.Actions>
</Card>
<Modal isVisible = {this.state.isModalVisible}>
<View>
<Text>Test</Text>
<Button title = "Cancel" onPress = {this.toggleModal}/>
</View>
</Modal>
</TouchableOpacity>
)}
keyExtractor = {item => item.key}
/>
</ScrollView>
<Button color = {'#5BC0EB'} onPress={popUpForm}>Add New Macro</Button>
</View>
);
}
}

According to your code, you need to pass your toggleModal function to TouchableOpacity in order to display your Model. Check below sample for more information.
import React, { Component } from 'react';
import { SafeAreaView, View, FlatList, StyleSheet, Text, TouchableOpacity, Modal, Button } from 'react-native';
const DATA = [
{
id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
title: 'First Item',
},
{
id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
title: 'Second Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'Third Item',
},
];
export default class App extends Component {
state = {
isModalVisible: false
}
toggleModal = () => {
this.setState({
isModalVisible: !this.state.isModalVisible
});
};
renderItem = ({ item }) => (
<TouchableOpacity style={styles.item} onPress={this.toggleModal}>
<Text style={styles.title}>{item.title}</Text>
</TouchableOpacity>
)
render() {
return (
<SafeAreaView style={styles.container}>
<FlatList
data={DATA}
renderItem={this.renderItem}
keyExtractor={item => item.id}
/>
{
this.state.isModalVisible &&
<Modal
visible={this.state.isModalVisible}
transparent={true}
animationType='slide'
onRequestClose={this.toggleModal}
>
<View style={styles.modelStyle}>
<View style={styles.modelWrapperStyle}>
<Text>Test</Text>
<Button title="Cancel" onPress={this.toggleModal} />
</View>
</View>
</Modal>
}
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 50,
},
item: {
backgroundColor: '#f9c2ff',
padding: 20,
marginVertical: 8,
marginHorizontal: 16,
},
title: {
fontSize: 32,
},
modelStyle: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'rgba(0, 0, 0, 0.5)'
},
modelWrapperStyle: {
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#ffffff',
padding: 20,
width: '90%'
}
});
Change this according to your requirement.
Hope this helps you. Feel free for doubts.

Related

How to send Selected Custom Checkbox data to next page in react native?

Here I have created toggle custom checkboxes and those are rendered within FlatList with Name.
Now which checkboxes are checked i want to send those names into next screen using navigation.
So how can i implement that functionality, if anyone knows then please help me for the same.
/**Code For custom checkbox:**/
import React from "react";
import {
TouchableOpacity,
Image,
View,
SafeAreaView,
Text,
} from "react-native";
import { useState } from "react";
import IconAntDesign from "react-native-vector-icons/AntDesign";
export function CheckBoxCustom() {
const [count, setCount] = useState(0);
return (
<SafeAreaView>
<TouchableOpacity
style={{
backgroundColor: "white",
width: 20,
height: 20,
borderWidth: 2,
borderColor: "#ddd",
}}
onPress={() => setCount(!count)}
>
{count ? (
<IconAntDesign name="check" size={15} color={"black"} />
) : null}
</TouchableOpacity>
</SafeAreaView>
);
}
/**Code for FlatList:**/
import React, {useState} from 'react';
import {
SafeAreaView,
Text,
View,
TouchableOpacity,
Image,
StyleSheet,
FlatList,
Dimensions,
useWindowDimensions,
ScrollView,
Button,
} from 'react-native';
import Header from '../CustomComponents/RestaurentUI/Header';
import {CheckBoxCustom} from '../CustomComponents/RestaurentUI/Checkbox';
import {TextInput} from 'react-native-gesture-handler';
import {TabView, SceneMap, TabBar} from 'react-native-tab-view';
import {NavigationContainer, useNavigation} from '#react-navigation/native';
import GetCheckBoxData from './GetCheckBoxData';
const data = [
{
name: 'Lumlère brûlée',
status: 'Problems',
},
{
name: 'Aucune eau chaude',
status: 'Problems',
},
{
name: 'Lumlère brûlée',
status: 'Problems',
},
{
name: 'Service de ménage',
status: 'Problems',
},
{
name: 'AC non-fonctionnel',
status: 'Problems',
},
{
name: 'WIFI non-fonctionnel',
status: 'Problems',
},
{
name: 'Four non-fonctionnel',
status: 'Problems',
},
];
const renderItem = ({item, index}) => {
return (
<View>
<View style={{flexDirection: 'row'}}>
<CheckBoxCustom />
<Text style={{marginLeft: 10}}>{item.name} </Text>
</View>
</View>
);
};
const separator = () => {
return (
<View
style={{
height: 1,
backgroundColor: '#f1f1f1',
marginBottom: 12,
marginTop: 12,
}}
/>
);
};
const FirstRoute = () => (
<FlatList
style={{marginTop: 20}}
data={data}
keyExtractor={(e, i) => i.toString()}
renderItem={renderItem}
ItemSeparatorComponent={separator}
/>
);
const SecondRoute = () => (
<View style={[styles.scene, {backgroundColor: 'white'}]} />
);
const initialLayout = {width: Dimensions.get('window').width};
const renderScene = SceneMap({
first: FirstRoute,
second: SecondRoute,
});
const ReportScreen = ({navigation}) => {
const nav = useNavigation();
const layout = useWindowDimensions();
const [index, setIndex] = useState(0);
const [routes] = useState([
{key: 'first', title: 'Problemes'},
{key: 'second', title: 'Besoins complémentaitaires'},
]);
const goToScreen = () => {
navigation.navigate('GetCheckBoxData', {title: 'Hii all'});
};
const [checked, setChecked] = useState({});
const checkToggle = id => {
setChecked(checked => ({
...checked,
[id]: !checked[id],
}));
};
return (
<SafeAreaView style={styles.safearea}>
<Header title="Report" />
<ScrollView showsVerticalScrollIndicator={false} bounces={false}>
<View style={{flexDirection: 'row', marginTop: 20}}>
<View style={{flex: 1, height: 1, backgroundColor: '#ccc'}} />
</View>
<View style={styles.cardView}>
<View style={styles.subView}>
<Image
style={styles.image}
source={require('../Assets/UIPracticeImage/H1.jpg')}
/>
<View style={styles.internalSubView}>
<View style={styles.nameView}>
<Text style={styles.nameText}>Pine Hill Green Caban</Text>
</View>
<View style={styles.dateView}>
<Text style={styles.dateText}>May 22-27</Text>
</View>
</View>
</View>
</View>
<View style={{flexDirection: 'row'}}>
<View style={{flex: 1, height: 1, backgroundColor: '#ccc'}} />
</View>
<View
style={{
// backgroundColor: 'lime',
flex: 1,
height: 385,
width: '100%',
}}>
<TabView
navigationState={{index, routes}}
renderScene={renderScene}
onIndexChange={setIndex}
initialLayout={initialLayout}
style={styles.container}
renderTabBar={props => (
<TabBar
tabStyle={{alignItems: 'flex-start', width: 'auto'}}
{...props}
renderLabel={({route, color}) => (
<Text style={{color: 'black'}}>{route.title}</Text>
)}
style={{backgroundColor: 'white'}}
/>
)}
/>
</View>
<Button title="Click me" onPress={goToScreen} />
</ScrollView>
</SafeAreaView>
);
};
export default ReportScreen;
const styles = StyleSheet.create({
safearea: {
marginHorizontal: 20,
},
cardView: {
borderRadius: 10,
marginVertical: 10,
paddingVertical: 8,
},
subView: {
flexDirection: 'row',
},
image: {
height: 80,
width: 110,
borderRadius: 10,
},
internalSubView: {
justifyContent: 'space-between',
flex: 1,
},
nameView: {
justifyContent: 'space-between',
flexDirection: 'row',
alignItems: 'center',
marginLeft: 10,
},
nameText: {
fontWeight: 'bold',
width: '45%',
fontSize: 15,
},
dateView: {
flexDirection: 'row',
alignItems: 'center',
marginLeft: 10,
justifyContent: 'space-between',
},
dateText: {
width: 80,
},
listTab: {
flexDirection: 'row',
marginBottom: 20,
marginTop: 20,
},
btnTab: {
borderWidth: 3,
borderColor: 'white',
flexDirection: 'row',
marginRight: 10,
},
btnTabActive: {
borderWidth: 3,
borderBottomColor: '#fdd83d',
borderColor: 'white',
},
scheduleButton: {
backgroundColor: '#fdd83d',
alignItems: 'center',
paddingVertical: 15,
borderRadius: 10,
marginTop: 15,
},
container: {
marginTop: 20,
},
scene: {
flex: 1,
},
});
[![UI image][1]][1]
[1]: https://i.stack.imgur.com/AuLT8.png
You may want to lift the checkbox state to the parent component, i.e. make the checkboxes controlled, and collect the checked checkbox values. For this I'm assuming your data items have an id property, but any unique item property will suffice.
Example:
export function CheckBoxCustom({ checked, onPress }) {
return (
<SafeAreaView>
<TouchableOpacity
style={{
backgroundColor: "white",
width: 20,
height: 20,
borderWidth: 2,
borderColor: "#ddd",
}}
onPress={onPress}
>
{checked ?? <IconAntDesign name="check" size={15} color={"black"} />}
</TouchableOpacity>
</SafeAreaView>
);
}
...
const [checked, setChecked] = useState({});
const checkToggle = id => {
setChecked(checked => ({
...checked,
[id]: !checked[id],
}));
};
const renderItem = ({ item, index }) => {
return (
<View>
<View style={{ flexDirection: "row" }}>
<CheckBoxCustom
checked={checked[item.id]}
onPress={() => checkToggle(item.id)}
/>
<Text style={{ marginLeft: 10 }}>{item.name}</Text>
</View>
</View>
);
};
<FlatList
data={dataList}
keyExtractor={(e, i) => i.toString()}
renderItem={renderItem}
ItemSeparatorComponent={separator}
/>;
If your data hasn't any good GUID candidates then I suggest augmenting your data to include good GUIDs.
To pass the checked/selected items filter the dataList array.
Example:
const selected = dataList.filter(
item => checked[item.id]
);
// pass selected in navigation action

React Native TouchableOpacity onPress using index/key of the item in FlatList

We created a FlatList component and a Contact screen in our app. We want to add 'heart' icon to the near of the images in Contact screen. We added heart icon near to all of items. But, if we pressed one of these icons, it changes all of theirs colors to red, not only one of them. We want to change the color of clicked item.
Screenshot of our program:
This is our FlatList component:
import React, { Component } from 'react';
import { View, Text, SafeAreaView, StyleSheet, FlatList, Image, TouchableOpacity,
TouchableWithoutFeedback, TextInput } from 'react-native';
import { Right, Icon } from 'native-base';
import data from '../../data';
export default class FlatListComponent extends Component {
state = {
text: '',
contacts: data,
like: false,
color: 'white',
}
toggleLike=()=>{
this.setState({
like: !this.state.like
})
if(this.state.like){
this.setState({
color: 'red',
})
}else{
this.setState({
color: 'white',
})
}
}
renderContactsItem = ({item, index}) => {
return (
<View style={[styles.itemContainer]}>
<Image
style={styles.avatar}
source={{ uri: item.image }} />
<View style={styles.textContainer}>
<Text style={[styles.name], {color: '#fafafa'}}>{item.first_name}</Text>
<Text style={{ color: '#fafafa' }}>{item.last_name}</Text>
</View>
<Right style={{justifyContent: 'center'}}>
<TouchableWithoutFeedback onPress={this.toggleLike}>
{/*{this.like ? (
<Icon name="heart" type='FontAwesome' style={{paddingRight: 10, fontSize: 30, color: 'red'}} />
) :
( <Icon name="heart" type='FontAwesome' style={{paddingRight: 10, fontSize: 30, color: 'white'}} /> )
}*/}
<Icon name='heart' type='FontAwesome' size={32} style={{color: this.state.color === "white" ? 'white' :'red', paddingRight: 10 }}/>
{/*<Icon name="heart" type='FontAwesome' style={{paddingRight: 10, fontSize: 30, color: this.state.color}} />*/}
</TouchableWithoutFeedback>
</Right>
</View>
);
}
searchFilter = text => {
const newData = data.filter(item => {
const listItems = `${item.first_name.toLowerCase()}`
return listItems.indexOf(text.toLowerCase()) > -1;
});
this.setState({
contacts: newData,
});
};
renderHeader = () => {
const {text} = this.state;
return (
<View style={styles.searchContainer}>
<TextInput
onChangeText = {text => {
this.setState ({
text,
});
this.searchFilter(text);
}}
value={text}
placeholder="Search..."
style={styles.searchInput} />
</View>
)
}
render() {
return (
<FlatList
ListHeaderComponent={this.renderHeader()}
renderItem={this.renderContactsItem}
keyExtractor={item => item.id}
data={this.state.contacts}
/>
);
}
}
const styles = StyleSheet.create({
itemContainer: {
flex: 1,
flexDirection: 'row',
paddingVertical: 10,
borderBottomWidth: 1,
borderBottomColor: '#eee'
},
avatar: {
width: 50,
height: 50,
borderRadius: 25,
marginHorizontal: 10,
},
textContainer: {
justifyContent: 'space-around',
},
name: {
fontSize: 16,
},
searchContainer: {
padding: 10
},
searchInput: {
fontSize: 16,
backgroundColor: '#f9f9f9',
padding: 10,
}
});
Our Contact screen is just:
import React from 'react';
import 'SafeAreaView' from 'react-native';
import FlatList from './FlatList';
export default function Contact() {
<SafeAreaView style={{ flex: 1 }}>
<FlatList />
</SafeAreaView>
}
How can we implement this?
I've run into this recently :) One option is to make the renderContactsItem its own component. For example:
const RenderContactsItem = ({item, index}) => {
const [like, setLike] = useState(false);
const [color, setColor] = useState("white");
const toggleLike = () => {
setLike(!like)
if(like) {
setColor("red");
} else {
setColor("white");
}
}
return (
<View style={[styles.itemContainer]}>
<Image
style={styles.avatar}
source={{ uri: item.image }} />
<View style={styles.textContainer}>
<Text style={[styles.name], {color: '#fafafa'}}>{item.first_name}</Text>
<Text style={{ color: '#fafafa' }}>{item.last_name}</Text>
</View>
<Right style={{justifyContent: 'center'}}>
<TouchableWithoutFeedback onPress={toggleLike}>
<Icon name='heart' type='FontAwesome' size={32} style={{color, paddingRight: 10 }}/>
</TouchableWithoutFeedback>
</Right>
</View>
);
}
In this case, each item manages its own state, so setting like doesn't set it for every item.
Another option would be to build an object with "like" states and set the values as the hearts are pressed. For example:
state = {
text: '',
contacts: data,
like: {},
color: 'white', // You don't need this
}
Then, when a heart is pressed, you can send toggleLike the index, and set the state like so:
toggleLike = (index) => {
let newLike = {...this.state.like};
newLike[index] = !Boolean(newLike[index]);
this.setState({
like: newLike,
});
}
And render the color conditionally depending on the index value of the like state, like so:
<Icon name='heart' type='FontAwesome' size={32} style={{color: this.state.like[index] ? 'red' :'white', paddingRight: 10 }}/>

Change color after click on TouchableHighlight in react native

I have done a many research on the color change after press/click. Finally
I got this script for change the state and put it in the TouchableHighlight. But When i clicked on that, only the "underlayColor={'gray'}" is working. Can i get some idea ?
here is my code
import React, { Component } from 'react';
import {
StyleSheet,
Text,
StatusBar ,
TouchableOpacity,
View,
FlatList,
ActivityIndicator,
TouchableHighlight,
PropTypes,
Image,
Alert
} from 'react-native';
import Logo from '../components/Logo';
import Form from '../components/Front';
import {Actions} from 'react-native-router-flux';
export default class Login extends Component<{}> {
constructor() {
super();
this.state = {
dataSource: {},
pressed: false
};
}
izijackpotconfirm() {
Actions.izijackpotconfirm()
}
componentDidMount() {
var that = this;
let items = Array.apply(null, Array(25)).map((v, i) => {
return { id: i+1 };
});
that.setState({
dataSource: items,
});
}
static navigationOptions = {
title: "Izi Jackpot",
headerStyle: {
backgroundColor: "#354247"
},
headerTintColor: "#fff",
headerTitleStyle: {
fontWeight: "bold"
}
};
render() {
var jackpotNumbers = [];
let btn_class = this.state.black ? "NormalSet" : "SelectedSet";
return(
<View style={styles.container}>
<View style={styles.middlecontainer}>
<Text style={styles.logoText}>Please Select 5 Numbers and Submit</Text>
</View>
<FlatList
data={this.state.dataSource}
renderItem={({ item }) => (
<View style={{ flex: 1, flexDirection: 'column', margin: 1 }}>
<TouchableHighlight
onPress={() => { Alert.alert(this.state.pressed) }}
style={[
styles.iziPizi,
this.state.pressed ? { backgroundColor: "blue" } : {}
]}
onHideUnderlay={() => {
this.setState({ pressed: false });
}}
onShowUnderlay={() => {
this.setState({ pressed: true });
}}
underlayColor={'gray'}
>
<Text style={styles.buttonText}>{ item.id}</Text></TouchableHighlight>
</View>
)}
//Setting the number of column
numColumns={5}
keyExtractor={(item, index) => index}
/>
<View style={styles.middlecontainer}>
<TouchableOpacity style={styles.button} onPress={this.izijackpotconfirm} >
<Text style={styles.buttonText}>Submit</Text>
</TouchableOpacity>
</View>
</View>
)
}
}
const styles = StyleSheet.create({
container : {
backgroundColor:'#6F9000',
justifyContent: 'center',
flex: 1,
paddingTop: 30,
},
middlecontainer: {
textAlign: 'center',
alignItems: 'center',
justifyContent :'center',
flex:1
},
signupTextCont : {
flexGrow: 1,
alignItems:'flex-end',
justifyContent :'center',
paddingVertical:16,
flexDirection:'row'
},
signupText: {
color:'rgba(255,255,255,0.6)',
fontSize:16
},
signupButton: {
color:'#ffffff',
fontSize:16,
fontWeight:'500'
},
iziPizi: {
width: 55,
padding: 15,
margin: 5,
borderRadius: 80,
borderWidth: 2,
borderColor: '#FFFFFF',
flex:1
},
iziPiziPress: {
width: 55,
padding: 15,
margin: 5,
backgroundColor:'#1c313a',
borderRadius: 80,
borderWidth: 2,
borderColor: '#FFFFFF',
flex:1
},
button: {
width:300,
backgroundColor:'#1c313a',
borderRadius: 25,
marginVertical: 10,
paddingVertical: 13
},
buttonText: {
fontSize:16,
fontWeight:'500',
color:'#ffffff',
textAlign:'center'
},
logoText : {
color:'#FFFFFF',
fontSize: 16,
fontWeight: '500',
alignItems: 'center',
justifyContent:'center',
},
imageThumbnail: {
justifyContent: 'center',
alignItems: 'center',
height: 100,
},
});
One more thing to say that, i have used FlatList here. Please help on this. Thanks in advance.
The problem is in how you work with the styles inside the Touchable. My advice is to create 2 styles that contain the changes:
style={
this.state.pressed ? styles.pressed : styles.iziPizi
}
Inside the touchable of course:
<TouchableHighlight
onPress={() => { Alert.alert(this.state.pressed) }}
style={
this.state.pressed ? styles.pressed : styles.iziPizi
}
onHideUnderlay={() => {
this.setState({ pressed: false });
}}
onShowUnderlay={() => {
this.setState({ pressed: true });
}}
underlayColor={'gray'}
>
yes. there was a problem in FlatList. but i dont know what is its problem.
use ListItem of native-base instead.
remember that if you want to use ListItem, in constructor change
this.state = {
dataSource: {},
...
}
to
this.state = {
dataSource: [],
}
use array insead. here is a sample code for you.
<View style={{ flex: 1, flexDirection: 'column', margin: 1 }}>
<List>
{this.state.dataSource.map( item =>
<ListItem>
<TouchableHighlight
onPress={() => {}}
onShowUnderlay={this.onPress.bind(this)}
>
<Text style={styles.buttonText}>{ item.id}</Text>
</TouchableHighlight>
</ListItem> )
}
</List>
</View>
Also define onPress method.
another problem in your code is this that you setState of pressed.
it results that all of your element style will be changed. so all of your button backgroundColor will be changed.
so you must define pressed flag for every element in your array and change this flag

how to display buttons under a scrollview in react native

good day everyone,
i'm working on this react-native project and i got a problem with the scrollView component and buttons positions. so basically i want to have 2 buttons, to either confirm or cancel my choice from the scrollView, underneath the scrollview and each one is filling half the width. both the buttons and the scrollview are found inside a modal.
i have tried every combination of flexbox and heights i managed to think of but nothing worked and the height of the section including the buttons is still way bigger than i want and buttons are not side by side.
this the component with the problem:
import React, { Component } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Modal, TouchableHighlight, ScrollView, FlatList } from 'react-native';
import { NavigationActions } from "react-navigation";
import genericStyle from '../../styles/generic-style';
import { colors, fontSizes } from '../../styles/base';
import values from '../../styles/responsive';
import NAVLogo from '../generic/NAVLogo';
export default class Welcome extends Component {
state = {
modalVisible: false,
values: [
{
id: 1,
text: "one"
},
{
id: 2,
text: "two"
},
{
id: 3,
text: "three"
},
{
id: 4,
text: "four"
},
{
id: 5,
text: "five"
},
{
id: 6,
text: "six"
},
{
id: 7,
text: "seven"
},
]
};
setModalVisible(visible) {
this.setState({ modalVisible: visible });
}
render() {
return (
<View style={[styles.welcome, genericStyle.centerContainer]}>
<Modal
animationType="slide"
transparent={true}
visible={this.state.modalVisible}
onRequestClose={() => {
Alert.alert("Modal has been closed.");
}}
>
<View style={styles.modal}>
<View style={styles.modalContent}>
<View style={styles.scrollViewStyle}>
<ScrollView style={styles.scrollViewStyle}>
{this.state.values.map((value, index) => (
<TouchableHighlight
onPress={() => console.log("TH1...")}
style={styles.company}
key={value.id}
>
<Text>{value.text}</Text>
</TouchableHighlight>
))}
</ScrollView>
</View>
<View
style={{
flex: 1,
flexDirection: "column",
height: "15%"
}}
>
<TouchableOpacity
onPress={() => {
this.setModalVisible(!this.state.modalVisible);
}}
>
<Text>confirm</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
this.setModalVisible(!this.state.modalVisible);
}}
>
<Text>cancel</Text>
</TouchableOpacity>
</View>
</View>
</View>
</Modal>
<NAVLogo />
<Text style={styles.text}>
Welcome
<Text style={styles.uname}>
{" " + this.props.navigation.getParam("uname", "Unknown")}
</Text>
</Text>
<TouchableOpacity
onPress={() => {
console.log("company");
this.setModalVisible(true);
}}
style={styles.btnContainer}
>
<View style={styles.btn}>
<Text style={styles.btnText}>Select Company</Text>
</View>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
console.log("log out");
this.props.navigation.dispatch(
NavigationActions.navigate({
routeName: "Home"
})
);
}}
style={styles.btnContainer}
>
<View style={styles.btn}>
<Text style={styles.btnText}> Log out </Text>
</View>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
welcome: {
backgroundColor: colors.sky
},
btn: {
width: "75%",
paddingVertical: 15,
backgroundColor: colors.darksky,
marginTop: values.mtb + 3,
alignItems: "center"
},
btnText: {
fontSize: values.fontSize + 2,
color: colors.light
},
btnContainer: {
width: "100%",
alignItems: "center"
},
text: {
fontSize: values.fontSize,
color: colors.dark,
fontWeight: "400",
marginVertical: 20
},
uname: {
fontWeight: "900",
fontSize: values.fontSize + 2
},
modalContent: {
width: "80%",
backgroundColor: colors.light,
flex: 0
},
modal: {
flex: 1,
alignItems: "center",
justifyContent: "center",
backgroundColor: "rgba(00,00,00,0.3)"
},
company: {
width: "100%",
borderBottomColor: colors.dark,
borderBottomWidth: 1,
paddingLeft: 35,
paddingVertical: 30
},
scrollViewStyle: {
flexGrow: 0,
flex: 0,
height: "85%"
}
});
this is the way the modal is displayed (i haven't worked that much on styling since i was stuck with positioning the buttons for the past 2 hours):
i hope someone can help me out with this. i'm new to react native so i'm pretty sure this is a trivial issue that i missed somewhere.
thanks to everyone in advance for the their time and help.
use flexDirection:'row' to make it side by side, and position:'absolute' to make it stay at the bottom
<View
style={{
position:'absolute',
bottom:10,
flexDirection: "row",
justifyContent:'space-between',
width:'100%'
}}>
<TouchableOpacity>
<Text> CONFIRM </Text>
</TouchableOpacity>
<TouchableOpacity>
<Text> CANCEL </Text>
</TouchableOpacity>
</View>

How to set the height of the image as the flex height

In my react-native application, I want to set the height of an image as the flex height. How can I do that? At present, Im using the height as the device-heigth / 3. But when it comes to the smaller screens, it makes issues. How can I achieve this as the height of the image as the flex height? My code works properly in 5 inch devices, but when it comes to 4, the image makes a mess.
render() {
return (
<View style={styles.container}>
<View style={styles.postCommentWrapper}>
<ScrollView
ref={view => {
this.scrollView = view;
}}
>
<Animated.View>
<PostProfileBar
profile={this.state.post.author}
timeAgo={this.state.post.timeAgo}
/>
<ClickableImage
source={{ uri: this.state.post.postImage }}
height={height * (3 / 10)}
width={width}
onPress={() => alert("Image Clicked")}
/>
</Animated.View>
<CommentFlatList
data={this.state.data}
refreshing={this.state.refreshing}
/>
</ScrollView>
</View>
<View
style={[
styles.commentInputWrapper,
{ flex: this.state.commentBoxStyles.flex }
]}
>
<InputWithClickableIcon
iconName="upload"
placeholder="Type Comment"
isFocused={true}
fontSize={this.state.comment.value.length > 0 ? 16 : 20}
value={this.state.comment.value}
multiline={true}
maxLength={500}
height={this.state.commentBoxStyles.height}
borderRadius={this.state.commentBoxStyles.borderRadius}
onChangeText={value => this.onChangeComment(value)}
onPress={() => this.uploadComment()}
invalidInput={styles.invalidInput}
valid={this.state.comment.valid}
touched={this.state.comment.touched}
disabled={!this.state.comment.valid}
/>
</View>
</View>
);
}
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
return {
headerTitle: "Comment",
headerTitleStyle: {
paddingLeft: "20%",
paddingRight: "20%"
},
headerStyle: {
paddingRight: 10,
paddingLeft: 10
},
headerLeft: (
<Icon
name={"close"}
size={30}
onChangeText={this.onChangeText}
onPress={() => {
navigation.goBack();
}}
/>
)
};
};
}
const styles = StyleSheet.create({
container: {
borderWidth: 3,
borderColor: "yellow",
flex: 1
},
postCommentWrapper: {
borderWidth: 2,
borderColor: "blue",
flex: 16,
marginTop: 10
},
// commentListWrapper: {
// borderWidth: 2,
// borderColor: "green",
// flex: 8,
// marginTop: 10
// },
commentInputWrapper: {
flex: 2,
borderWidth: 2,
borderColor: "purple",
justifyContent: "flex-end",
marginTop: 5
}
});
ClickableImage Component
import React from "react";
import { TouchableOpacity, Image, StyleSheet } from "react-native";
const clickableImage = props => (
<TouchableOpacity onPress={props.onPress}>
<Image
{...props}
style={[
styles.image,
props.style,
{ height: props.height },
{ width: props.width }
]}
/>
</TouchableOpacity>
);
const styles = StyleSheet.create({
image: {
marginTop: 10,
flexDirection: "row",
alignItems: "center"
}
});
export default clickableImage;
Since you've already passed the style props to the ClickableImage, therefore you can do
<ClickableImage
source={{ uri: this.state.post.postImage }}
style={{flex: 1}}
onPress={() => alert("Image Clicked")}
/>
You also need to pass the styles to TouchableOpacity for the flex inside the container to work
<TouchableOpacity style={props.style} onPress={props.onPress}> //... Pass the relevant styles here