Align all icon to the right of page regardless of start point React Native - react-native

I want to be able to align all reply icons to the far right, where the red line is, regardless of where they start.
Edit: added more information to show how recursion is used in the component. Why I try to use some answers that work without recursion, I receive an undesired effect.
This is the code I have in place so far:
class Comment extends Component {
render() {
return(
<View>
<Header
rounded
style={{
backgroundColor: '#ffffff',
position: 'relative',
}}
>
<View style={{flexDirection: 'row', flexWrap: 'wrap', right: '43%', top: '50%'}}>
<Icon name='chevron-left' size={10} color='#006FFF' style={{top: '6%'}}/>
<NativeText
onPress={() => this.props.history.push('/')}
style ={{color: '#006FFF', fontSize: 12, fontFamily: 'Montserrat-Regular'}}
>
Back
</NativeText>
</View>
</Header>
<View
style={{paddingLeft: '2%', paddingTop: '2%'}}
>
<CommentList
options={this.props.location.state.comments}
currentUser={this.props.location.state.currentUser}
history={this.props.history}
reportId={this.props.location.state.reportId}
optionsForBackButton={this.props.location.state.comments}
/>
</View>
</View>
)
}
}
export default withRouter(Comment)
const CommentList = ({options, currentUser, history, reportId, optionsForBackButton}) => {
return (
<View>
{options.map(option => (
<View
style={{flexDirection: 'row'}}
>
<NativeText
style={{fontSize: 12, fontFamily: 'Montserrat-Regular'}}
>
{option.content}
</NativeText>
<View
style={{flex: 1, alignItems: 'flex-end' }}
>
<Icon
name='reply'
size={12}
// onPress={() => {
// setModalVisible(true)
// changeParentId(option._id)
// }}
onPress={() => history.push({pathname: '/create-comment', state: {content: option.content, currentUser: currentUser, reportId: reportId, parentCommentId: option._id, optionsForBackButton: optionsForBackButton}})}
/>
</View>
{
<View
style={{left: '10%'}}
>
<CommentList
options={option.reply}
optionsForBackButton={optionsForBackButton}
history={history}
currentUser={currentUser}
reportId={reportId}
/>
</View>
}
</View>
))}
</View>
)
}

Set your icon containing view's flex value to 1. This should cause it to fill all remaining space.
See the following snack: https://snack.expo.io/#jrdndncn/playful-churros
class Comment extends React.Component {
render() {
return (
<View
style={{
marginVertical: 2,
flexDirection: 'row',
marginLeft: (this.props.indent || 0) * 20,
}}>
<Text>{this.props.text}</Text>
<View style={{ flex: 1, alignItems: 'flex-end' }}>
<View style={{ width: 20, height: 20, backgroundColor: 'red' }} />
</View>
</View>
);
}
}
<Comment text="hello" indent={0} />
<Comment text="hello" indent={1} />
<Comment text="hello" indent={2} />

Basically marginLeft:'auto' will do the trick. just add style to icon as :
<Icon
name='reply'
size={12}
style={{marginLeft:'auto'}}
// onPress={() => {
// setModalVisible(true)
// changeParentId(option._id)
// }}
onPress={() => history.push({pathname: '/create-comment', state: {content: option.content, currentUser: currentUser, reportId: reportId, parentCommentId: option._id, optionsForBackButton: optionsForBackButton}})}
/>
i added marginLeft:'auto' in style it will automatically shown at the right end of the screen.

Related

React Native Flatlist ListHeaderComponent Doesn't Work

ListHeaderComponent inside flatlist doesn't work. It won't render nothing in header (above flatlist). If I however put some custom component it does work but it doesn't with my renderHeader function. I tried making a custom component with the same view as in renderHeader but when I used that nothing rendered so I don't know
My flatlist along with whole render:
render() {
const { height } = Dimensions.get("window");
return (
<View style={{flex: 1,
backgroundColor: "#EBECF4"}}>
{/* <Text>
Connection Status :{" "}
{this.state.connection_status ? "Connected" : "Disconnected"}
</Text> */}
{/* <Loader loading={this.state.loading} /> */}
<StatusBar backgroundColor="#63003d" barStyle="light-content" />
<SafeAreaView>
<ModernHeader
backgroundColor="#63003d"
height={50}
text="Eleph"
textStyle={{
color: "white",
fontFamily: "Lobster-Regular",
//fontWeight: "bold",
fontSize: 25,
}}
leftIconComponent={
<TouchableOpacity
style={{ marginRight: 0, margin: 0 }}
onPress={() =>
this.props.navigation.dispatch(DrawerActions.openDrawer())
}
>
<FontAwesome5 name="bars" size={22} color="white" />
</TouchableOpacity>
}
rightIconComponent={
<TouchableOpacity
style={{ marginLeft: 0, margin: 0 }}
onPress={() => this.props.navigation.navigate("Profile")}
>
{/* <MaterialCommunityIcons
name="chart-areaspline"
size={24}
color="#639dff"
/> */}
<Foundation name="graph-bar" size={24} color="white" />
{/* <FontAwesome name="bar-chart" size={24} color="white" /> */}
</TouchableOpacity>
}
/>
</SafeAreaView>
<FlatList
//contentInset={{ top: HEADER_HEIGHT }}
//contentOffset={{ y: -HEADER_HEIGHT }}
data={this.state.post}
extraData={this.state.post}
keyExtractor={(item) => item.id.toString()}
style={{
marginHorizontal: 0,
marginVertical: 6,
}}
renderItem={({ item }) => this.renderPost(item)}
ListFooterComponent={this.renderFooter}
ListHeaderComponent={this.renderHeader}
refreshControl={
<RefreshControl
style={{ color: "#639dff" }}
tintColor="#639dff"
titleColor="#fff"
refreshing={this.state.isLoading}
onRefresh={this.onRefresh}
/>
}
initialNumToRender={7}
onEndReachedThreshold={0.1}
showsVerticalScrollIndicator={false}
onEndReached={() => {
if (
!this.onEndReachedCalledDuringMomentum &&
!this.state.isMoreLoading
) {
this.getMore();
}
}}
onMomentumScrollBegin={() => {
this.onEndReachedCalledDuringMomentum = false;
}}
onScroll={(e) => {
scrollY.setValue(e.nativeEvent.contentOffset.y);
}}
></FlatList>
{/* <View style={styles.footer}>
<TouchableOpacity
activeOpacity={0.9}
onPress={this.getMore}
style={styles.loadMoreBtn}
>
<Text style={styles.btnText}>See more moods</Text>
{this.state.loading ? (
<ActivityIndicator color="white" style={{ marginLeft:8 }} />
) : null}
</TouchableOpacity>
</View> */}
</SafeAreaView>
</View>
My renderHeader function:
renderHeader = () => {
return (
<View
style={{
flex: 1,
flexDirection: "row",
backgroundColor: "#ffffff",
//width: "100%",
padding: 11,
alignItems: "center",
position: "absolute",
justifyContent: "center",
//top: 50,
//bottom: 0,
//left: 0,
//elevation: 4,
//right: 0,
//height: 50,
}}
//flexDirection: "row",
//backgroundColor: "#ffffff",
//width: "100%",
//padding: 11,
//alignItems: "center",
>
<TouchableOpacity
onPress={() => this.props.navigation.navigate("Post")}
>
<Text
style={{ alignItems: "center", color: "#C4C6CE" }}
//placeholder={How are you feeling right now ${this.state.user.name}?}
multiline
>{Tell us how are you feeling right now ${this.state.user.name}?}</Text>
</TouchableOpacity>
{/* <View style={styles.divider}></View> */}
</View>
);
}
Why for example renderFooter works??
renderFooter = () => {
if (!this.state.isMoreLoading) return true;
return (
<ActivityIndicator
size="large"
color={"#D83E64"}
style={{ marginBottom: 10 }}
/>
);
};
Use ListHeaderComponentStyle to style the ListHeaderComponent.
I created a simple snack for you, check if this helps. Your code looks okay but not sure about the whole screen design. Here is my snack link.
https://snack.expo.io/#saad-bashar/excited-fudge
It might be related to the other components inside your screen. So first check only with flatlist, remove all other components. Hope you can sort it out :)
The solution is to remove the "absolute" style in the header for flatlist. The question is mine im just answering with different account but this is the solution that worked.

react native Modal opening from last object in array

I am creating a render method where it displays information from a state array, and I want it so that when a user touches a Card a Modal will open presenting the same information.
My code is as follows:
this.state = {
fontLoaded: false,
feed: [{
username: ["Jeff", "Kyle", "David"],
caption: ["Great", "Amazing", "Not so Good"],
comments: ["Comment 1", "Comment 2", "No Comment"],
photo:[Pic1,Pic2,Pic3],
}]
}
state = {
isModalVisible: false,
};
toggleModal = () => {
this.setState({ isModalVisible: !this.state.isModalVisible });
};
renderFeed = () => {
return this.state.feed.map((card, index) => {
return card.username.map((username, i) => {
if(card.caption[i])
return (
<View>
<TouchableHighlight onPress={this.toggleModal} underlayColor="white">
<Card
key={`${i}_${index}`}
image={card.photo[i]}
containerStyle={{borderRadius:10, marginRight:1, marginLeft:1,}}>
<View
style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between' }}
>
<View style={{ flexDirection: 'row'}}>
<Avatar
size="small"
rounded
source={card.photo[i]}
/>
</View>
<View style={{flexDirection:'row'}}>
<Avatar
rounded
icon={{ name:'heart-multiple-outline', type:'material-community', color: '#ff4284'}}
overlayContainerStyle={{marginLeft:5}}
reverse
size='small'/>
<Avatar
reverse
rounded
icon={{ name:'comment-processing-outline', type:'material-community' }}
overlayContainerStyle={{backgroundColor: '#dbdbdb',marginLeft:5}}
size='small'/>
</View>
</View>
{ this.state.fontLoaded == true ? (
<View style={{flexDirection:'row'}}>
<Text style={{fontFamily: 'MontserratB', color:'#bf00b9', marginTop:10}}>{username}</Text>
<Text style={{fontFamily:'Montserrat', marginTop:10}}>{card.caption[i]}</Text>
</View>
) : (<Text> Loading...</Text>)
}
<Text style={{marginTop:4, color:'#878787'}}>{card.comments[i]}</Text>
</Card>
</TouchableHighlight>
<Modal
animationIn="zoomInDown"
animationOut="zoomOutDown"
animationInTiming={700}
animationOutTiming={600}
backdropTransitionInTiming={600}
backdropTransitionOutTiming={600}
isVisible={this.state.isModalVisible}>
<Image source={card.photo[i]}
style={{width: SCREEN_WIDTH - 20,
height: 300, justifyContent: 'center', alignSelf:
'center' }}/>
<Card
containerStyle={{ width: SCREEN_WIDTH - 20, marginTop: 0, justifyContent: 'center', alignSelf:
'center' }}>
<View style={{ flexDirection:'row' }}>
<Avatar
size="small"
rounded
source={card.photo[i]}
/>
<View style={{ flex:2, flexDirection:'row', justifyContent:'flex-end' }}>
<Avatar
rounded
icon={{ name:'heart-multiple-outline', type:'material-community'}}
overlayContainerStyle={{backgroundColor: '#ff4284',marginLeft:5}}
reverse
size='small'/>
<Avatar
reverse
rounded
icon={{ name:'comment-processing-outline', type:'material-community' }}
overlayContainerStyle={{backgroundColor: '#dbdbdb',marginLeft:5}}
size='small'/>
</View>
</View>
<View style={{ flexDirection:'row' }}>
<Text style={{fontFamily: 'MontserratB', color:'#bf00b9', marginTop:10}}>{username}</Text>
<Text style={{fontFamily:'Montserrat', marginTop:10}}>{card.caption[i]}</Text>
</View>
<Text style={{marginTop:4, color:'#878787'}}>{card.comments[i]}</Text>
</Card>
<Button style={{marginTop:0, borderBottomRightRadius: 20, borderBottomLeftRadius: 20, borderTopLeftRadius: 0, borderTopRightRadius: 0, width: SCREEN_WIDTH - 20, alignSelf: 'center', justifyContent: 'center'}} title="Close" onPress={this.toggleModal} />
</Modal>
</View>
);
return <React.Fragment />;
});
})
}
everything works perfectly except that no matter which Card is touched a Modal is opened presenting the last objects in the array. So no matter which of the three cards are pressed, a Modal will always open with the information regarding David
Modified snack version of your sample:
https://snack.expo.io/H1yHPQQdr

How to fix keyboard from hiding input fields in React Native

I’m setting up a new component,
and the keyboard covers the fields
This is for a new component
<KeyboardAwareScrollView enableOnAndroid={true} extraScrollHeight={50} enableAutomaticScroll={true}>
<View style={{ paddingHorizontal: 20 }}>
<View>
<FloatingLabelInput
onRef={(ref) => {
this.inputs['firstName'] = ref
}}
onSubmitEditing={() => {
this.focusNextField('lastName')
}}
label={i18n.t('t_driver_registration_first_name_label')}
onChangeText={(text) => this.onChangeInputText('firstName', text)}
keyboardType='default'
maxLength={20}
value={form.firstName}
labelStyle={Style.inputLabel}
basicColor={GStyle.GREEN}
inputTextColor={Color(GStyle.BLACK).alpha(.7)}
editable={mode !== DriverFormMode.EDIT}
/>
I expect the keyboard will not cover my fields.
Wrap your view in this to scroll automatically on input focus. Do:
<KeyboardAvoidingView style={{ flex: 1, flexDirection: 'column',justifyContent: 'center',}} behavior="padding" enabled keyboardVerticalOffset={100}>
<ScrollView>
<View style={Styles.row}>
//your view
</View>
</ScrollView>
</KeyboardAvoidingView>
<View style={Styles.row}> This is just a Stylesheet e.g. Create a new StyleSheet:
const Styles = StyleSheet.create({
row: {
borderRadius: 4,
borderWidth: 0.5,
borderColor: '#d6d7da',
},
title: {
fontSize: 19,
fontWeight: 'bold',
},
activeTitle: {
color: 'red',
},
});
Use a StyleSheet:
<View style={Styles.row}>
<Text style={[Styles.title, this.props.isActive && styles.activeTitle]} />
</View>

Disable user interaction during activityindicator. React-Native

I want to disable user interaction when the activity indicator is running. The user should not be able to type again in the TextInput and disable touchableopacity button.
render() {
return (
<View style={styles.container}>
<View style={styles.backgroundContainer}>
<Image
source={require("./background-image.jpg")}
resizeMode="cover"
style={styles.backdrop}
/>
</View>
<View style={styles.contentContainer}>
<View style={styles.subContainer}>
<Image style={styles.image} source={require("./logo.png")} />
<TextInput
// editable={!this.props.isLoginLoading}
style={styles.input}
ref={"input1"}
placeholder="Enter your mobile number"
maxLength={10}
onChangeText={value => this.setState({ mobilenumber: value })}
/>
<TouchableOpacity
// activeOpacity={this.getOpacity()} //newly added
onPress={this.onPress}
>
<View style={styles.button}>
<Text style={styles.buttonText}>Login</Text>
</View>
</TouchableOpacity>
</View>
{this.props.isLoginLoading && (
<View style={styles.indicator}>
<ActivityIndicator color={"blue"} />
</View>
)}
</View>
</View>
);
}
}
Below shows the design for the above code, styles.js
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
backgroundColor: "#FFFFFF"
},
backgroundContainer: {
position: "absolute",
top: 0,
bottom: 0,
left: 0,
right: 0
},
contentContainer: {
flex: 1,
alignItems: "center",
justifyContent: "center"
},
subContainer: {
alignItems: "center"
},
backdrop: {
flex: 1
},
image: {
marginBottom: Metrics.screenHeight * 0.075,
resizeMode: "contain",
width: Metrics.screenWidth * 0.35,
height: Metrics.screenHeight * 0.25
},
input: {
borderWidth: 1,
marginBottom: Metrics.screenWidth * 0.03,
width: Metrics.screenWidth * 0.626,
backgroundColor: "lightgrey"
},
button: {
width: Metrics.screenWidth * 0.626,
height: Metrics.screenHeight * 0.06,
alignItems: "center",
backgroundColor: "#8c0d04",
fontWeight: "bold"
},
buttonText: {
padding: Metrics.screenHeight * 0.0165,
color: "#FFFFFF",
fontWeight: "bold",
alignItems: "center",
justifyContent: "center"
},
indicator: {
position: "absolute",
left: 0,
right: 0,
top: 0,
bottom: 0,
// width: "100%",
// height: "100%",
justifyContent: "center",
alignItems: "center"
// borderWidth: 5,
// borderColor: "yellow"
}
});
export default styles;
I used dimensions to get the screen height and screen width according to the device size and added style to the activity indicator to by writing position to 'absolute' but still I'm able to access the text input as well the button click. I want to achieve the following thing when the user clicks the login button, I need to show the activity indicator below the Login button and I have to disable user interaction during the activity indicator.
There is two way you can achieve this.
If you want ActivityIndicator below of button then just remove view which contains {{flex:1}} style. and only give marginTop style to the parent view of ActivityIndicator. For that, you have to disable TextInput and button manually. Please see below code.
export default class Example extends Component {
onPress() {
if (!this.props.isLoginLoading) {
// skip if isLoginLoading is true
}
}
getOpacity() {
if (this.props.isLoginLoading) {
return 1;
}
return 0
}
render() {
return (
<View style={styles.container}>
<View style={styles.backgroundContainer}>
<Image source={require('./background-image.jpg')} resizeMode='cover' style={styles.backdrop} />
</View>
<View>
<View>
<Image
style={styles.image}
source={require('./logo.png')}
/>
</View>
<View style={styles.textinputview}>
<TextInput
editable={!this.props.isLoginLoading} //do editable false when loading is true
style={styles.input}
ref={'input1'}
placeholder='Enter your mobile number'
maxLength={10}
onChangeText={value => this.setState({ mobilenumber: value })}
/>
</View>
<View style={styles.touchableview}>
<TouchableOpacity
activeOpacity={this.getOpacity()} //set activopacity to 1 to indicate button is disable, when loading is true
onPress={this.onPress.bind(this)}>
<View style={styles.button}>
<Text style={styles.buttonText}>Login</Text>
</View>
</TouchableOpacity>
</View>
</View>
{this.props.isLoginLoading &&
<View
style={{
marginTop:10
}} >
<ActivityIndicator color={'blue'} />
</View>
}
</View>
);
}
}
just remove view which contains flex:{1} style. which will include ActivityIndicator in the center of the screen
return (
<View style={styles.backgroundContainer}>
<Image source={require('./background-image.jpg')} resizeMode='cover' style={styles.backdrop} />
</View>
<View>
<View>
<Image
style={styles.image}
source={require('./logo.png')}
/>
</View>
<View style={styles.textinputview}>
<TextInput
style={styles.input}
ref={'input1'}
placeholder='Enter your mobile number'
maxLength={10}
onChangeText={value => this.setState({ mobilenumber: value })}
/>
</View>
<View style={styles.touchableview}>
<TouchableOpacity onPress={this.onPress}>
<View style={styles.button}>
<Text style={styles.buttonText}>Login</Text>
</View>
</TouchableOpacity>
</View>
</View>
{this.props.isLoginLoading &&
<View
style={{
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
width:'100%',
height:'100%',
justifyContent: 'center',
alignItems: 'center'
}}>
<ActivityIndicator color={'blue'} />
</View>
}
</View>
)

Like functionality like Facebook react native

I am using a list of image.Below every image,there is a like button. When i click on the Like button, likes should be increases which is working fine. But it should work on the image I click. Currently it is increasing like count of all the images.I am new to react native.Any help would be appreciated.
Here, this is my code
export default class Art extends Component {
constructor(props) {
super(props)
this.state = {
value: null,
liked:false
}
}
_increaseValue(){
console.log(this.state.liked)
if (this.state.liked==false)
{
this.setState({liked: !this.state.liked})
newvalue =this.state.value +1;
this.setState({value:newvalue})
}
else
{
this.setState({liked: !this.state.liked})
newvalue =this.state.value -1;
this.setState({value:newvalue}
}
}
render() {
const datas = [
{
img: images[0]
},
{
img: images[1]
},
{
img: images[2]
},
{
img: images[3]
},
];
const { navigate } = this.props.navigation;
// eslint-disable-line
return (
<Content padder style={{ marginTop: 0, backgroundColor: '#3b5998' }}>
<List
style={{ marginLeft: -19, marginRight: -19 }}
dataArray={datas}
renderRow={data =>
<ListItem >
<Card
wrapperStyle={{ marginLeft: -10, marginTop: -10, marginRight: -10, }} containerStyle={{ marginLeft: 2, marginTop: -5, }}>
<TouchableOpacity activeOpacity={.5} onPress={() => navigate('ImageDisplay',{item:data})}>
<Image source={{ uri: data.img }} style={[styles.imageContainer, styles.image]}/>
</TouchableOpacity>
<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-around', marginTop: 20 }}>
<View style={{flexDirection:'row'}}>
<TouchableOpacity activeOpacity={.5} onPress={() => {this._increaseValue()}}>
<View>
{this.state.liked ? <Icon active name="favorite" style={styles.iconCountContainer} color='red' size={14}/>
: <Icon name="favorite" style={styles.iconCountContainer} size={14}/>}
</View></TouchableOpacity>
<Text style={{color:'#000000',fontSize:15, marginLeft:12, marginTop:5}}>{this.state.value} Likes </Text>
</View>
<View style={styles.iconCountContainer}>
<Icon active name="share" size={14} style={styles.share} onPress={() => Share.open(shareOptions).catch((err) => { err && console.log(err); })} />
</View>
</View>
</Card>
</ListItem>
}
/>
</Content>
);
}
}
You need to convert your Cards into separate components or store the like counts separately in state. You can approach this problem several ways. I'll give you an example of how you can achieve this behavior and you can implement it the way you like.
Example
export default class CutomListItem extends React.Component {
constructor(props) {
this.state = {
likes: 0
};
}
_increaseValue = () => {
this.setState((prevState) => {
return {
likes: prevState.likes++
};
});
}
render() {
const { data, navigate, share } = this.props; // send data with props
<ListItem >
<Card
wrapperStyle={{ marginLeft: -10, marginTop: -10, marginRight: -10, }} containerStyle={{ marginLeft: 2, marginTop: -5, }}>
<TouchableOpacity activeOpacity={.5} onPress={() => navigate('ImageDisplay',{item:data})}>
<Image source={{ uri: data.img }} style={[styles.imageContainer, styles.image]}/>
</TouchableOpacity>
<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-around', marginTop: 20 }}>
<View style={{flexDirection:'row'}}>
<TouchableOpacity activeOpacity={.5} onPress={() => {this._increaseValue()}}>
<View>
{this.state.liked ? <Icon active name="favorite" style={styles.iconCountContainer} color='red' size={14}/>
: <Icon name="favorite" style={styles.iconCountContainer} size={14}/>}
</View></TouchableOpacity>
<Text style={{color:'#000000',fontSize:15, marginLeft:12, marginTop:5}}>{this.state.likes} Likes </Text>
</View>
<View style={styles.iconCountContainer}>
<Icon active name="share" size={14} style={styles.share} onPress={() => Share.open(shareOptions).catch((err) => { err && console.log(err); })} />
</View>
</View>
</Card>
</ListItem>
}
}
return (
<Content padder style={{ marginTop: 0, backgroundColor: '#3b5998' }}>
<List
style={{ marginLeft: -19, marginRight: -19 }}
dataArray={datas}
renderRow={data => (<CutomListItem data={data} navigate={navigate} share={Share} />}
/>
</Content>
);
}