Bottom navigation in react native - reactjs

here is image
can we make this kind of bottom navigation in react native specially the shape on navigation? can I make this kind of bottom navigation specially the wave on it

You can make your custom bottom bar
Working example: https://snack.expo.io/#msbot01/happy-waffle
(You can adjust code as per required UI)
Example code
import React, { Component } from 'react';
import {View, Text, StyleSheet, Image, TouchableOpacity, Dimensions} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome5';
import Dashboard from './Dashboard';
import Gift from './Gift';
import Like from './Like';
var width = Dimensions.get('window').width
var tabs = [
{
key: 'home',
icon: 'home',
label: 'Home',
barColor: '#388E3C',
pressColor: 'rgba(255, 255, 255, 0.16)',
badgeCount: 0
},
{
key: 'heart',
icon: 'calendar-check',
label: 'Heart',
barColor: '#B71C1C',
pressColor: 'rgba(255, 255, 255, 0.16)',
badgeCount: 2
},
{
key: 'location',
icon: 'users',
label: 'Location',
barColor: '#E64A19',
pressColor: 'rgba(255, 255, 255, 0.16)',
badgeCount: 2
}
]
export default class SupervisorDashboard extends Component<Props> {
constructor(props) {
super(props);
this.state = {
userData: global.userData,
selectedTab: 'home',
}
}
componentDidMount(){
}
dateSelected(e){
this.setState({
selectedDate: e
})
}
homePressed(){
console.log('Home____')
this.setState({
selectedTab: 'home'
})
}
heartPressed(){
console.log('heart____')
this.setState({
selectedTab: 'heart'
})
}
locationPressed(){
console.log('Location____')
this.setState({
selectedTab: 'location'
})
}
renderScene(){
switch(this.state.selectedTab) {
case ('home'):{
return <Dashboard/>
}
break;
case ('heart'):{
return <Like/>
}
break;
case ('location'):{
return <Gift/>
}
break;
}
}
renderMenuIcons(){
var tempArray = []
for (var i =0; i < tabs.length; i++) {
var a = tabs[i].key
console.log(a)
var eachElement;
switch(tabs[i].key) {
case ('home'):{
console.log('I am in home++++++++++')
eachElement = <TouchableOpacity key={i} style={{alignItems:'center', justifyContent:'center'}} onPress={()=>{this.homePressed()}}>
<Icon name = {tabs[i].icon} size={20} light color={this.state.selectedTab==tabs[i].key? 'red' : 'grey'}/>
</TouchableOpacity>
}
break;
case ('heart'):{
console.log('I am in approvals+++++++++++')
eachElement = <TouchableOpacity key={i} style={{alignItems:'center', justifyContent:'center', marginBottom:30, backgroundColor:'green', height:50, width:50, borderRadius:30}} onPress={()=>{this.heartPressed()}}>
<Icon name={tabs[i].icon} size={25} light color={'white'}/>
</TouchableOpacity>
}
break;
case ('location'):{
console.log('I am in location+++++++++++++')
eachElement = <TouchableOpacity key={i} style={{alignItems:'center', justifyContent:'center'}} onPress={()=>{this.locationPressed()}}>
<Icon name={tabs[i].icon} size={20} light color={this.state.selectedTab==tabs[i].key? 'red' : 'grey'}/>
</TouchableOpacity>
}
break;
default:{
console.log('+++++++++++++++++'+tabs[i].key)
}
}
tempArray.push(eachElement)
}
return tempArray;
}
render(){
return(
<View style={{flex:1, backgroundColor: global.backGroundColor}}>
{this.renderScene()}
<View style={styles.oval}>
</View>
<View style={{width:'90%', alignItems:'center', height:70, flexDirection:'row', justifyContent:'space-around', marginLeft:'5%', marginRight:'5%', position:'absolute', bottom:10, borderRadius:30, borderColor: global.borderColor, backgroundColor:global.backGroundColor}}>
{this.renderMenuIcons()}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
background: {
backgroundColor: 'red'
},
oval: {
width: (0.78*width),
height: (0.78*width),
borderRadius: 150,
//backgroundColor: 'red',
borderWidth:1,
borderColor:'#e4e4e4',
transform: [
{scaleX: 1.5}
],
marginLeft:45,
marginTop:150,
position:'absolute',
bottom:-200
}
});

Related

Issue with messages rendering a view specific to onLongPress

I am trying to render a View through renderCustomView={this.displayEmojis} for an individual message once a user has activated the onLongPress={} function. However, the view im trying to display repeats for every single message on the screen, rather than the one pressed. I have attached what happens when I try to press on a message with multiple messages showing:
//EventPost
import React from 'react'
import { Platform, View, StatusBar, TouchableOpacity, Text, Image, StyleSheet } from 'react-native'
import { getStatusBarHeight } from 'react-native-status-bar-height';
import { GiftedChat } from 'react-native-gifted-chat'
import emojiUtils from 'emoji-utils'
import KeyboardSpacer from 'react-native-keyboard-spacer';
import SlackMessage from './SlackMessage'
import Keyboard from 'react-native';
export default class EventPosts extends React.Component {
constructor(props) {
super(props);
this.state = {
messages: [],
toggle: false,
reactedMessage: 0,
reacted: false,
images: [
require("../assets/emojis/beer_photo.png"),
require("../assets/emojis/party_photo.png"),
require("../assets/emojis/laughing-emoji_photo.png"),
require("../assets/emojis/happy_photo.png"),
require("../assets/emojis/crying_photo.png"),
],
id: 0,
}
this.displayEmojis = this.displayEmojis.bind(this);
}
componentDidMount() {
this.setState({
messages: [
{
_id: 1,
text: 'I cant wait for this birthday party',
createdAt: new Date(),
user: {
_id: 2,
name: 'Andrew Garrett',
avatar: 'https://placeimg.com/140/140/any',
},
},
],
});
}
onSend(messages = []) {
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, messages),
}))
}
renderMessage(props) {
const {
currentMessage: { text: currText },
} = props
let messageTextStyle
if (currText && emojiUtils.isPureEmojiString(currText)) {
messageTextStyle = {
fontSize: 28,
lineHeight: Platform.OS === 'android' ? 34 : 30,
}
}
return (<SlackMessage {...props} messageTextStyle={messageTextStyle} />)
}
dismiss = () =>
Keyboard.dismiss();
updateEmojiCount(number) {
switch (number) {
case 1:
this.setState({ reactedMessage: 0 });
break;
case 2:
this.setState({ reactedMessage: 1 });
break;
case 3:
this.setState({ reactedMessage: 2 });
break;
case 4:
this.setState({ reactedMessage: 3 });
break;
case 5:
this.setState({ reactedMessage: 4 });
break;
default:
this.forceUpdate();
}
this.setState({ reacted: true });
this.setState({ toggle: false })
}
beerEmoji() {
return (
<View>
<TouchableOpacity style={styles.emojiContainer}
onPress={() => this.updateEmojiCount(1)}>
<Image style={styles.emoji} source={require("../assets/emojis/beer.gif")} />
</TouchableOpacity>
</View>
)
}
partyEmoji() {
return (
<View>
<TouchableOpacity style={styles.emojiContainer}
onPress={() => this.updateEmojiCount(2)}>
<Image style={styles.emoji} source={require("../assets/emojis/party.gif")} />
</TouchableOpacity>
</View>
)
}
laughingEmoji() {
return (
<View>
<TouchableOpacity onPress={() => this.updateEmojiCount(3)} style={styles.emojiContainer}>
<Image style={[styles.emoji, styles.emojiResize]} source={require("../assets/emojis/laughing-emoji.gif")} />
</TouchableOpacity>
</View>
)
}
happyEmoji() {
return (
<View>
<TouchableOpacity onPress={() => this.updateEmojiCount(4)} style={styles.emojiContainer}>
<Image style={[styles.emoji, styles.emojiResize]} source={require("../assets/emojis/happy.gif")} />
</TouchableOpacity>
</View>
)
}
cryingEmoji() {
return (
<View>
<TouchableOpacity onPress={() => this.updateEmojiCount(5)} style={styles.emojiContainer}>
<Image style={[styles.emoji, styles.emojiResize]} source={require("../assets/emojis/crying.gif")} />
</TouchableOpacity>
</View>
)
}
displayEmojis() {
if (this.state.toggle) {
return (
<View
style={{
flexDirection: 'row',
right: '35%',
backgroundColor: 'white',
zIndex: 3,
overlayColor: 'white',
borderRadius: 30,
paddingHorizontal: '10%',
bottom: '2%'
}}>
{this.beerEmoji()}
{this.partyEmoji()}
{this.laughingEmoji()}
{this.happyEmoji()}
{this.cryingEmoji()}
</View>
)
}
}
toggleEmojis = (context, message) => {
let temp = this.state.messages.filter(temp => message._id == temp._id);
let id = temp[0]._id;
this.setState({ id: temp[0]._id })
if (this.state.toggle) { this.setState({ toggle: false }) }
else { this.setState({ toggle: true }) }
}
render() {
return (
<View style={{ flex: 1 }}>
<View
style={{ paddingTop: Platform.OS === "android" ? StatusBar.currentHeight : getStatusBarHeight() }}>
<View style={{ backgroundColor: '#2c3e50', paddingVertical: '4%' }}>
<TouchableOpacity style={{ left: "89%", top: '0%' }} onPress={() => this.props.navigation.goBack()}>
<Text style={{ color: 'white' }}>Done</Text>
</TouchableOpacity>
</View>
</View>
<GiftedChat
keyboardShouldPersistTaps={'handled'}
messages={this.state.messages}
onSend={messages => this.onSend(messages)}
placeholder={"Post something..."}
isKeyboardInternallyHandled={false}
multiline={true}
extraData={this.state}
alwaysShowSend={true}
onLongPress={this.toggleEmojis}
user={{ _id: 1 }}
renderCustomView={this.displayEmojis}
renderMessage={this.renderMessage} />
<KeyboardSpacer />
</View>
)
}
}
const styles = StyleSheet.create({
emojiContainer: {
width: 55,
height: 55,
paddingHorizontal: '13%',
right: '15%'
},
emoji: {
width: 55,
height: 55,
borderRadius: 20,
},
emojiResize: {
transform: [{ scale: 0.75 }],
},
emojiReacted: {
transform: [{ scale: 0.4 }],
},
})
//SlackMessage
import PropTypes from 'prop-types';
import React from 'react';
import {
View,
ViewPropTypes,
StyleSheet,
Image
} from 'react-native';
import { Avatar, Day, utils } from 'react-native-gifted-chat';
import Bubble from './SlackBubble';
const { isSameUser, isSameDay } = utils;
export default class Message extends React.Component {
state = {
images: [
require("../assets/emojis/beer_photo.png"),
require("../assets/emojis/party_photo.png"),
require("../assets/emojis/laughing-emoji_photo.png"),
require("../assets/emojis/happy_photo.png"),
require("../assets/emojis/crying_photo.png"),
]
}
getInnerComponentProps() {
const { containerStyle, ...props } = this.props;
return {
...props,
position: 'left',
isSameUser,
isSameDay,
};
}
renderDay() {
if (this.props.currentMessage.createdAt) {
const dayProps = this.getInnerComponentProps();
if (this.props.renderDay) {
return this.props.renderDay(dayProps);
}
return <Day {...dayProps} />;
}
return null;
}
renderBubble() {
const bubbleProps = this.getInnerComponentProps();
if (this.props.renderBubble) {
return this.props.renderBubble(bubbleProps);
}
return <Bubble {...bubbleProps} />;
}
renderAvatar() {
let extraStyle;
if (
isSameUser(this.props.currentMessage, this.props.previousMessage)
&& isSameDay(this.props.currentMessage, this.props.previousMessage)
) {
extraStyle = { height: 0 };
}
const avatarProps = this.getInnerComponentProps();
return (
<Avatar
{...avatarProps}
imageStyle={{ left: [styles.slackAvatar, avatarProps.imageStyle, extraStyle] }}
/>
);
}
render() {
const marginBottom = isSameUser(this.props.currentMessage, this.props.nextMessage) ? 2 : 10;
const { images } = this.state
const index = (this.props.extraData.reactedMessage);
return (
<View>
{this.renderDay()}
<View
style={[
styles.container,
{ marginBottom },
this.props.containerStyle,
]}>
{this.renderAvatar()}
{this.renderBubble()}
{<Image source={images[index]} style={{ width: 20, height: 20, right: '8%' }} />}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
alignItems: 'flex-end',
justifyContent: 'flex-start',
marginLeft: 8,
marginRight: 8,
backgroundColor: 'white',
borderWidth: 2,
borderColor: '#BEBEBE',
paddingBottom: '3%'
},
slackAvatar: {
height: 40,
width: 40,
borderRadius: 3,
left: '10%',
bottom: '12%'
},
});
Message.defaultProps = {
renderAvatar: undefined,
renderBubble: null,
renderDay: null,
currentMessage: {},
nextMessage: {},
previousMessage: {},
user: {},
containerStyle: {},
};
Message.propTypes = {
renderAvatar: PropTypes.func,
renderBubble: PropTypes.func,
renderDay: PropTypes.func,
currentMessage: PropTypes.object,
nextMessage: PropTypes.object,
previousMessage: PropTypes.object,
user: PropTypes.object,
containerStyle: PropTypes.shape({
left: ViewPropTypes.style,
right: ViewPropTypes.style,
}),
};
//Bubble
import PropTypes from 'prop-types';
import React from 'react';
import {
Text,
Clipboard,
StyleSheet,
TouchableOpacity,
View,
ViewPropTypes,
Platform,
} from 'react-native';
import { MessageText, MessageImage, Time, utils } from 'react-native-gifted-chat';
const { isSameUser, isSameDay } = utils;
export default class Bubble extends React.Component {
constructor(props) {
super(props);
this.onLongPress = this.onLongPress.bind(this);
}
onLongPress() {
if (this.props.onLongPress) {
this.props.onLongPress(this.context, this.props.currentMessage);
} else {
if (this.props.currentMessage.text) {
const options = [
'Copy Text',
];
const cancelButtonIndex = options.length - 1;
this.context.actionSheet().showActionSheetWithOptions({
options,
cancelButtonIndex,
},
(buttonIndex) => {
switch (buttonIndex) {
case 0:
Clipboard.setString(this.props.currentMessage.text);
break;
}
});
}
}
}
renderMessageText() {
if (this.props.currentMessage.text) {
const { containerStyle, wrapperStyle, messageTextStyle, ...messageTextProps } = this.props;
if (this.props.renderMessageText) {
return this.props.renderMessageText(messageTextProps);
}
return (
<MessageText
{...messageTextProps}
textStyle={{
left: [styles.standardFont, styles.slackMessageText, messageTextProps.textStyle, messageTextStyle],
}}
/>
);
}
return null;
}
renderMessageImage() {
if (this.props.currentMessage.image) {
const { containerStyle, wrapperStyle, ...messageImageProps } = this.props;
if (this.props.renderMessageImage) {
return this.props.renderMessageImage(messageImageProps);
}
return <MessageImage {...messageImageProps} imageStyle={[styles.slackImage, messageImageProps.imageStyle]} />;
}
return null;
}
renderTicks() {
const { currentMessage } = this.props;
if (this.props.renderTicks) {
return this.props.renderTicks(currentMessage);
}
if (currentMessage.user._id !== this.props.user._id) {
return null;
}
if (currentMessage.sent || currentMessage.received) {
return (
<View style={[styles.headerItem, styles.tickView]}>
{currentMessage.sent && <Text style={[styles.standardFont, styles.tick, this.props.tickStyle]}>✓</Text>}
{currentMessage.received && <Text style={[styles.standardFont, styles.tick, this.props.tickStyle]}>✓</Text>}
</View>
);
}
return null;
}
renderUsername() {
const username = this.props.currentMessage.user.name;
if (username) {
const { containerStyle, wrapperStyle, ...usernameProps } = this.props;
if (this.props.renderUsername) {
return this.props.renderUsername(usernameProps);
}
return (
<Text style={[styles.standardFont, styles.headerItem, styles.username, this.props.usernameStyle]}>
{username}
</Text>
);
}
return null;
}
renderTime() {
if (this.props.currentMessage.createdAt) {
const { containerStyle, wrapperStyle, ...timeProps } = this.props;
if (this.props.renderTime) {
return this.props.renderTime(timeProps);
}
return (
<Time
{...timeProps}
containerStyle={{ left: [styles.timeContainer] }}
textStyle={{ left: [styles.standardFont, styles.headerItem, styles.time, timeProps.textStyle] }}
/>
);
}
return null;
}
renderCustomView() {
if (this.props.renderCustomView) {
return this.props.renderCustomView(this.props);
}
return null;
}
render() {
const isSameThread = isSameUser(this.props.currentMessage, this.props.previousMessage)
&& isSameDay(this.props.currentMessage, this.props.previousMessage);
const messageHeader = isSameThread ? null : (
<View style={styles.headerView}>
{this.renderUsername()}
{this.renderTime()}
{this.renderTicks()}
</View>
);
return (
<View style={[styles.container, this.props.containerStyle]}>
<TouchableOpacity
onLongPress={this.onLongPress}
accessibilityTraits="text"
{...this.props.touchableProps}
>
<View
style={[
styles.wrapper,
this.props.wrapperStyle,
]}
>
<View>
{this.renderCustomView()}
{messageHeader}
{this.renderMessageImage()}
{this.renderMessageText()}
</View>
</View>
</TouchableOpacity>
</View>
);
}
}
// Note: Everything is forced to be "left" positioned with this component.
// The "right" position is only used in the default Bubble.
const styles = StyleSheet.create({
standardFont: {
fontSize: 15,
},
slackMessageText: {
marginLeft: 0,
marginRight: 0,
},
container: {
flex: 1,
alignItems: 'flex-start',
},
wrapper: {
marginRight: 60,
minHeight: 20,
justifyContent: 'flex-end',
},
username: {
fontWeight: 'bold',
},
time: {
textAlign: 'left',
fontSize: 12,
},
timeContainer: {
marginLeft: 0,
marginRight: 0,
marginBottom: 0,
},
headerItem: {
marginRight: 10,
},
headerView: {
// Try to align it better with the avatar on Android.
marginTop: Platform.OS === 'android' ? -2 : 0,
flexDirection: 'row',
alignItems: 'baseline',
},
/* eslint-disable react-native/no-color-literals */
tick: {
backgroundColor: 'transparent',
color: 'white',
},
/* eslint-enable react-native/no-color-literals */
tickView: {
flexDirection: 'row',
},
slackImage: {
borderRadius: 3,
marginLeft: 0,
marginRight: 0,
},
});
Bubble.contextTypes = {
actionSheet: PropTypes.func,
};
Bubble.defaultProps = {
touchableProps: {},
onLongPress: null,
renderMessageImage: null,
renderMessageText: null,
renderCustomView: null,
renderTime: null,
currentMessage: {
text: null,
createdAt: null,
image: null,
},
nextMessage: {},
previousMessage: {},
containerStyle: {},
wrapperStyle: {},
tickStyle: {},
containerToNextStyle: {},
containerToPreviousStyle: {},
};
Bubble.propTypes = {
touchableProps: PropTypes.object,
onLongPress: PropTypes.func,
renderMessageImage: PropTypes.func,
renderMessageText: PropTypes.func,
renderCustomView: PropTypes.func,
renderUsername: PropTypes.func,
renderTime: PropTypes.func,
renderTicks: PropTypes.func,
currentMessage: PropTypes.object,
nextMessage: PropTypes.object,
previousMessage: PropTypes.object,
user: PropTypes.object,
containerStyle: PropTypes.shape({
left: ViewPropTypes.style,
right: ViewPropTypes.style,
}),
wrapperStyle: PropTypes.shape({
left: ViewPropTypes.style,
right: ViewPropTypes.style,
}),
messageTextStyle: Text.propTypes.style,
usernameStyle: Text.propTypes.style,
tickStyle: Text.propTypes.style,
containerToNextStyle: PropTypes.shape({
left: ViewPropTypes.style,
right: ViewPropTypes.style,
}),
containerToPreviousStyle: PropTypes.shape({
left: ViewPropTypes.style,
right: ViewPropTypes.style,
}),
};

Why is only the last component in array animating?

Goal: create an OptionFan button that when pressed, rotates on its Z axis, and FanItems release from behind the main button and travel along their own respective vectors.
OptionFan.js:
import React, { useState, useEffect } from 'react';
import { Image, View, Animated, StyleSheet, TouchableOpacity, Dimensions } from 'react-native';
import EStyleSheet from 'react-native-extended-stylesheet';
import FanItem from './FanItem';
const { height, width } = Dimensions.get('window');
export default class OptionFan extends React.Component {
constructor (props) {
super(props);
this.state = {
animatedRotate: new Animated.Value(0),
expanded: false
};
}
handlePress = () => {
if (this.state.expanded) {
// button is opened
Animated.spring(this.state.animatedRotate, {
toValue: 0
}).start();
this.refs.option.collapse();
this.setState({ expanded: !this.state.expanded });
} else {
// button is collapsed
Animated.spring(this.state.animatedRotate, {
toValue: 1
}).start();
this.refs.option.expand();
this.setState({ expanded: !this.state.expanded });
}
};
render () {
const animatedRotation = this.state.animatedRotate.interpolate({
inputRange: [ 0, 0.5, 1 ],
outputRange: [ '0deg', '90deg', '180deg' ]
});
return (
<View>
<View style={{ position: 'absolute', left: 2, top: 2 }}>
{this.props.options.map((item, index) => (
<FanItem ref={'option'} icon={item.icon} onPress={item.onPress} index={index} />
))}
</View>
<TouchableOpacity style={styles.container} onPress={() => this.handlePress()}>
<Animated.Image
resizeMode={'contain'}
source={require('./src/assets/img/arrow-up.png')}
style={{ transform: [ { rotateZ: animatedRotation } ], ...styles.icon }}
/>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
justifyContent: 'center',
alignItems: 'center',
borderRadius: 30,
backgroundColor: '#E06363',
elevation: 15,
shadowOffset: {
height: 3,
width: 3
},
shadowColor: '#333',
shadowOpacity: 0.5,
shadowRadius: 5,
height: width * 0.155,
width: width * 0.155
},
icon: {
height: width * 0.06,
width: width * 0.06
},
optContainer: {
justifyContent: 'center',
alignItems: 'center',
borderRadius: 30,
backgroundColor: '#219F75',
elevation: 5,
shadowOffset: {
height: 3,
width: 3
},
shadowColor: '#333',
shadowOpacity: 0.5,
shadowRadius: 5,
height: width * 0.13,
width: width * 0.13,
position: 'absolute'
}
});
FanItem.js:
import React, { useState } from 'react';
import { Image, Animated, StyleSheet, TouchableOpacity, Dimensions } from 'react-native';
import EStyleSheet from 'react-native-extended-stylesheet';
const { width } = Dimensions.get('window');
export default class FanItem extends React.Component {
constructor (props) {
super(props);
this.state = {
animatedOffset: new Animated.ValueXY(0),
animatedOpacity: new Animated.Value(0)
};
}
expand () {
let offset = { x: 0, y: 0 };
switch (this.props.index) {
case 0:
offset = { x: -50, y: 20 };
break;
case 1:
offset = { x: -20, y: 50 };
break;
case 2:
offset = { x: 20, y: 50 };
break;
case 3:
offset = { x: 75, y: -20 };
break;
}
Animated.parallel([
Animated.spring(this.state.animatedOffset, { toValue: offset }),
Animated.timing(this.state.animatedOpacity, { toValue: 1, duration: 600 })
]).start();
}
collapse () {
Animated.parallel([
Animated.spring(this.state.animatedOffset, { toValue: 0 }),
Animated.timing(this.state.animatedOpacity, { toValue: 0, duration: 600 })
]).start();
}
render () {
return (
<Animated.View
style={
(this.props.style,
{
left: this.state.animatedOffset.x,
top: this.state.animatedOffset.y,
opacity: this.state.animatedOpacity
})
}
>
<TouchableOpacity style={styles.container} onPress={this.props.onPress}>
<Image resizeMode={'contain'} source={this.props.icon} style={styles.icon} />
</TouchableOpacity>
</Animated.View>
);
}
}
const styles = StyleSheet.create({
container: {
justifyContent: 'center',
alignItems: 'center',
borderRadius: 30,
backgroundColor: '#219F75',
elevation: 5,
shadowOffset: {
height: 3,
width: 3
},
shadowColor: '#333',
shadowOpacity: 0.5,
shadowRadius: 5,
height: width * 0.13,
width: width * 0.13,
position: 'absolute'
},
icon: {
height: width * 0.08,
width: width * 0.08
}
});
Implementation:
import React from 'react';
import { StyleSheet, View, Dimensions } from 'react-native';
import Component from './Component';
const { height, width } = Dimensions.get('window');
const testArr = [
{
icon: require('./src/assets/img/chat.png'),
onPress: () => alert('start chat')
},
{
icon: require('./src/assets/img/white_video.png'),
onPress: () => alert('video chat')
},
{
icon: require('./src/assets/img/white_voice.png'),
onPress: () => alert('voice chat')
},
{
icon: require('./src/assets/img/camera.png'),
onPress: () => alert('request selfie')
}
];
const App = () => {
return (
<View style={styles.screen}>
<Component options={testArr} />
</View>
);
};
const styles = StyleSheet.create({
screen: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#E6E6E6'
}
});
export default App;
Problem: The issue is, only the last FanItem item runs its animation. (opacity, and vector translation). before implementing the opacity animation I could tell the first three FanItems did in fact render behind the main button, because I could see them when pressing the main button, as the opacity temporarily changes for the duration of the button click.
My question is 1) why are the first three mapped items not animating? and 2) how to resolve this?
You are storing ref of FanItem in option. but, ref gets overridden in each iteration of map. so, at the end it only stores ref of last FanItem in option. So, first declare one array in constructor to store ref of each FanItem:
constructor(props) {
super(props);
// your other code
this.refOptions = [];
}
Store ref of each FanItem separately like this:
{this.props.options.map((item, index) => (
<FanItem ref={(ref) => this.refOptions[index] = ref} icon={item.icon} onPress={item.onPress} index={index} />
))}
and then to animate each FanItem:
for(var i = 0; i < this.refOptions.length; i++){
this.refOptions[i].expand(); //call 'expand' or 'collapse' as required
}
This is expo snack link for your reference:
https://snack.expo.io/BygobuL3JL

React Navigation doesn't change screen

I'm trying to navigate to another screen (Artist) by clicking on an element in a FlatList. This FlatList contains Artist instances, as set in the _renderListItem method. So far I've tried three different approaches (two of them commented out at the moment), but none of them seem to work:
Method 1: NavigationActions
Method 2: this.props.navigation.navigate
Method 3: Navigator.push
I managed to pass the params to the other screen, but unfortunately the navigation itself doesn't seem to work; I'm getting the expected values in my logs, but nothing happens and the app stays at LinksScreen (doesn't change screens).
LinksScreen.js
import React, { Component } from 'react';
import { PropTypes } from 'prop-types';
import Artist from './Artist';
import { createStackNavigator, withNavigation, NavigationActions } from 'react-navigation';
import {
ScrollView,
StyleSheet,
View,
Text,
Image,
FlatList,
ActivityIndicator,
TouchableOpacity,
TouchableHighlight,
} from 'react-native';
export default class LinksScreen extends React.Component {
constructor(props) {
super(props);
this._onAlertTypePressed = this._onAlertTypePressed.bind(this);
}
_onAlertTypePressed(typeId: string, typeName: string, imageUrl: string) {
console.log(typeId)
console.log(typeName)
console.log(imageUrl)
// NavigationActions
// NavigationActions.navigate({
// routeName: 'Artist',
// params: { itemId: typeId, itemName: typeName, itemImageUrl: imageUrl,},
// });
// NAVIGATE
this.props.navigation.navigate('HomeStack',{},
{
type: "Navigate",
routeName: "Artist",
params: {
itemId: typeId,
itemName: typeName,
itemImageUrl: imageUrl}
}
);
// PUSH
// this.props.navigator.push({
// screen: 'Artist',
// title: 'Artist',
// passProps: {
// itemId: typeId,
// itemName: typeName,
// itemImageUrl: imageUrl,
// },
// });
}
_renderListItem = ({item}) => (
<Artist
itemId={item.id}
itemName={item.title.rendered}
itemImageUrl={
item.better_featured_image
? item.better_featured_image.source_url
: 'http://54.168.73.151/wp-content/uploads/2018/04/brand-logo.jpg'
}
onPressItem={this._onAlertTypePressed}
/>
);
static navigationOptions = {
title: 'Links',
};
state = {
data: [],
isLoading: true,
isError: false,
};
// static propTypes = {
// navigation: PropTypes.shape({
// navigate: PropTypes.func.isRequired,
// }).isRequired,
// };
componentWillMount() {
fetch('http://54.168.73.151/wp-json/wp/v2/pages?parent=38&per_page=100')
.then(response => response.json())
.then(responseJson => {
responseJson.sort(
(a, b) => (a.title.rendered < b.title.rendered ? -1 : 1)
);
this.setState({
data: responseJson,
isLoading: false,
isError: false,
});
})
.catch(error => {
this.setState({
isLoading: false,
isError: true,
});
console.error(error);
});
}
// Not used anymore.
renderRow = item => (
<View style={styles.grid}>
<Image
style={styles.thumb}
source={{
uri: item.better_featured_image
? item.better_featured_image.source_url
: 'http://54.168.73.151/wp-content/uploads/2018/04/brand-logo.jpg',
}}
/>
<Text style={styles.title}>{item.title.rendered}</Text>
</View>
);
getKey = item => String(item.id);
renderComponent() {
if (this.state.isLoading) {
return <ActivityIndicator />;
} else if (this.state.isError) {
return <Text>Error loading data</Text>;
} else {
return (
<FlatList
numColumns={3}
contentContainerStyle={styles.elementsContainer}
data={this.state.data}
renderItem={this._renderListItem}
keyExtractor={this.getKey}
/>
);
}
}
render() {
return (
<View style={styles.container}>
<Text
style={{
fontSize: 20,
color: '#FFFFFF',
marginLeft: 4,
marginTop: 10,
}}>
RESIDENTS
</Text>
{this.renderComponent()}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#000000',
},
elementsContainer: {
backgroundColor: '#000000',
},
grid: {
marginTop: 15,
marginBottom: 15,
marginLeft: 5,
height: 125,
width: 115,
borderBottomWidth: 1,
borderBottomColor: '#191970',
},
title: {
color: '#FFFFFF',
textAlign: 'left',
fontSize: 12,
},
thumb: {
height: 110,
width: 110,
resizeMode: 'cover',
},
});
Artist.js
The console.log in the beginning of the _onPress() method seem to be working (the expected params have the correct values here), but I'm unable to navigate to this screen.
import React, { Component } from 'react';
import { createStackNavigator } from 'react-navigation';
import {
ScrollView,
StyleSheet,
View,
Text,
TouchableOpacity,
Image,
} from 'react-native';
class Artist extends React.PureComponent {
_onPress = () => {
// console.log(this.props)
const itemId = this.props.itemId
const itemName = this.props.itemName
const itemImageUrl = this.props.itemImageUrl
console.log(itemId)
console.log(itemName)
console.log(itemImageUrl)
// FOR PUSH
// this.props.onPressItem(
// this.props.itemid,
// this.props.itemName,
// this.props.itemImageUrl,
// );
// };
}
static navigationOptions = {
title: 'Artist',
};
render() {
return (
<TouchableOpacity
{...this.props}
style={styles.grid}
onPress={this._onPress}>
<Image
style={styles.image}
source={{uri: this.props.itemImageUrl}}
/>
<Text style={styles.title}>{this.props.itemName}</Text>
</TouchableOpacity>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#000000',
},
grid: {
marginTop: 15,
marginBottom: 15,
marginLeft: 5,
height: 125,
width: 115,
borderBottomWidth: 1,
borderBottomColor: '#191970',
},
title: {
color: '#FFFFFF',
textAlign: 'left',
fontSize: 12,
},
image: {
height: 110,
width: 110,
resizeMode: 'cover',
},
});
export default Artist;
MainTabNavigator.js
Perhaps there is something wrong regarding the routing, so here is how it's done in my case.
import React from 'react';
import { Platform, AppRegistry } from 'react-native';
import { createStackNavigator, createBottomTabNavigator } from 'react-navigation';
import TabBarIcon from '../components/TabBarIcon';
import HomeScreen from '../screens/HomeScreen';
import LinksScreen from '../screens/LinksScreen';
import SettingsScreen from '../screens/SettingsScreen';
import Artist from '../screens/Artist';
const HomeStack = createStackNavigator({
Home: {
screen: HomeScreen,
},
Links: {
screen: LinksScreen,
},
Artist: {
screen: Artist,
},
});
AppRegistry.registerComponent('ParamsRepo', () => HomeStack);
export default HomeStack;
Try simplyfying your code like this:
this.props.navigation.navigate('Artist',
{
itemId: typeId,
itemName: typeName,
itemImageUrl: imageUrl
}
});

Navigator is not working properly in React Native

I followed one tutorial for react native development tutorial.They developed one IOS app using react native.In there they had used NavigatorIOS for navigation purpose.IOS app is working properly.But when I need to create android app I have to changed it to NavigatorIOS to Navigator.App loaded first view.but later on that is not working.
Here [https://www.raywenderlich.com/126063/react-native-tutorial][1] the link of tutorial which I have followed.How can I change code for Android.?
import React, { Component } from 'react';
import {
StyleSheet,
Text,
TextInput,
View,
TouchableHighlight,
ActivityIndicator,
Image
} from 'react-native';
var SearchResults = require('./SearchResults');
function urlForQueryAndPage(key, value, pageNumber) {
var data = {
country: 'uk',
pretty: '1',
encoding: 'json',
listing_type: 'buy',
action: 'search_listings',
page: pageNumber
};
data[key] = value;
var querystring = Object.keys(data)
.map(key => key + '=' + encodeURIComponent(data[key]))
.join('&');
return 'http://api.nestoria.co.uk/api?' + querystring;
};
class SearchPage extends Component {
constructor(props) {
super(props);
this.state = {
searchString: 'london',
isLoading: false,
message: ''
};
}
onSearchTextChanged(event) {
console.log('onSearchTextChanged');
this.setState({ searchString: event.nativeEvent.text });
console.log(this.state.searchString);
}
_executeQuery(query) {
console.log(query);
this.setState({ isLoading: true });
fetch(query)
.then(response => response.json())
.then(json => this._handleResponse(json.response))
.catch(error =>
this.setState({
isLoading: false,
message: 'Something bad happened ' + error
}));
}
onLocationPressed() {
navigator.geolocation.getCurrentPosition(
location => {
var search = location.coords.latitude + ',' + location.coords.longitude;
this.setState({ searchString: search });
var query = urlForQueryAndPage('centre_point', search, 1);
this._executeQuery(query);
},
error => {
this.setState({
message: 'There was a problem with obtaining your location: ' + error
});
});
}
_handleResponse(response) {
this.setState({ isLoading: false , message: '' });
if (response.application_response_code.substr(0, 1) === '1') {
this.props.navigator.push({
title: 'Results',
component: SearchResults,
passProps: {listings: response.listings}
});
} else {
this.setState({ message: 'Location not recognized; please try again.'});
}
}
onSearchPressed() {
var query = urlForQueryAndPage('place_name', this.state.searchString, 1);
this._executeQuery(query);
}
render() {
var spinner = this.state.isLoading ?
( <ActivityIndicator
size='large'/> ) :
( <View/>);
console.log('SearchPage.render');
return (
<View style={styles.container}>
<Text style={styles.description}>
Search for houses to buy!
</Text>
<Text style={styles.description}>
Search by place-name, postcode or search near your location.
</Text>
<View style={styles.flowRight}>
<TextInput
style={styles.searchInput}
value={this.state.searchString}
onChange={this.onSearchTextChanged.bind(this)}
placeholder='Search via name or postcode'/>
<TouchableHighlight style={styles.button}
underlayColor='#99d9f4'
onPress={this.onSearchPressed.bind(this)}>
<Text style={styles.buttonText}>Go</Text>
</TouchableHighlight>
</View>
<View style={styles.flowRight}>
<TouchableHighlight style={styles.button}
underlayColor='#99d9f4'
onPress={this.onLocationPressed.bind(this)}>
<Text style={styles.buttonText}>Location</Text>
</TouchableHighlight>
</View>
<Image source={require('./Resources/house.png')} style={styles.image}/>
{spinner}
<Text style={styles.description}>{this.state.message}</Text>
</View>
);
}
}
var styles = StyleSheet.create({
description: {
marginBottom: 20,
fontSize: 18,
textAlign: 'center',
color: '#656565'
},
container: {
padding: 30,
marginTop: 80,
alignItems: 'center'
},
flowRight: {
flexDirection: 'row',
alignItems: 'center',
alignSelf: 'stretch'
},
buttonText: {
fontSize: 18,
color: 'white',
alignSelf: 'center'
},
button: {
height: 36,
flex: 1,
flexDirection: 'row',
backgroundColor: '#48BBEC',
borderColor: '#48BBEC',
borderWidth: 1,
borderRadius: 8,
marginBottom: 10,
alignSelf: 'stretch',
justifyContent: 'center'
},
searchInput: {
height: 36,
padding: 4,
marginRight: 5,
flex: 4,
fontSize: 18,
borderWidth: 1,
borderColor: '#48BBEC',
borderRadius: 8,
color: '#48BBEC'
},image: {
width: 217,
height: 138
}
});
module.exports = SearchPage;

How to get state value from constructor in ES6?

I'm trying to move forward with ES6 syntax but I've got an error trying to retrieve state value.
So my question is : how to get the state value in ES6? Here is a part of the code:
constructor(props) {
super(props);
this.state = {
timeElapsed: null,
isRunning: false
}
}
Then when I try to get isRunning state, it gives me this error: Cannot read property 'isRunning' of undefined.
if (this.state.isRunning) {
clearInterval(this.interval);
this.setState({
isRunning: false
});
return
}
Any idea? Thanks.
EDIT (here is the full code):
import React, {Component} from 'react';
import {
Text,
View,
AppRegistry,
StyleSheet,
TouchableHighlight
} from 'react-native';
import Moment from 'moment';
import formatTime from 'minutes-seconds-milliseconds';
class StopWatch extends Component {
constructor(props) {
super(props);
this.state = {
timeElapsed: null,
isRunning: false
}
}
render() {
return (
<View style={styles.container}>
<View style={styles.header}>
<View style={styles.timerWrapper}>
<Text style={styles.timer}>{formatTime(this.state.timeElapsed)}</Text>
</View>
<View style={styles.buttonWrapper}>
{this.startStopButton()}
{this.lapButton()}
</View>
</View>
<View style={styles.footer}>
<Text>List of laps</Text>
</View>
</View>
)
}
startStopButton() {
var style = this.state.isRunning ? styles.startButton : styles.stopButton;
return (
<TouchableHighlight style={[styles.button, style]} onPress={this.handleStartPress} underlayColor="gray">
<Text>{this.state.isRunning ? 'Stop' : 'Start'}</Text>
</TouchableHighlight>
)
}
lapButton() {
return (
<TouchableHighlight style={[styles.button, styles.lapButton]} onPress={this.lapPress} underlayColor="gray">
<Text>Lap</Text>
</TouchableHighlight>
)
}
border(color) {
return {
borderColor: color,
borderWidth: 4
}
}
handleStartPress() {
console.log('Start was pressed');
if (this.state.isRunning) {
clearInterval(this.interval);
this.setState({
isRunning: false
});
return
}
var startTime = new Date();
this.interval = setInterval(
()=>{
this.setState({
timeElapsed: new Date() - startTime
})
}, 30
);
this.setState({
isRunning: true
})
}
lapPress() {
console.log('Lap was pressed');
}
}
var styles = StyleSheet.create({
container: { // Main container
flex: 1,
alignItems: 'stretch'
},
header: { // Yellow
flex: 2
},
footer: { // Blue
flex: 3
},
timerWrapper: {
flex: 5,
justifyContent: 'center',
alignItems: 'center'
},
timer: {
fontSize: 60
},
buttonWrapper: {
flex: 3,
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center'
},
button: {
borderWidth: 2,
height: 100,
width: 100,
borderRadius: 50,
justifyContent: 'center',
alignItems: 'center'
},
startButton: {
borderColor: 'red'
},
stopButton: {
borderColor: 'green'
},
lapButton: {
borderColor: 'blue'
}
});
// AppRegistry.registerComponent('stopWatch', function() {
// return StopWatch;
// });
AppRegistry.registerComponent('stopwatch', () => StopWatch);
EDIT 2:
Here is a combined solution with and without binding in constructor:
import React, {Component} from 'react';
import {
Text,
View,
AppRegistry,
StyleSheet,
TouchableHighlight
} from 'react-native';
import Moment from 'moment';
import formatTime from 'minutes-seconds-milliseconds';
class StopWatch extends Component {
constructor(props) {
super(props);
this.state = {
timeElapsed: null,
isRunning: false
}
this.startStopButton = this.startStopButton.bind(this)
this.lapButton = this.lapButton.bind(this)
}
render() {
return (
<View style={styles.container}>
<View style={styles.header}>
<View style={styles.timerWrapper}>
<Text style={styles.timer}>{formatTime(this.state.timeElapsed)}</Text>
</View>
<View style={styles.buttonWrapper}>
{this.startStopButton()}
{this.lapButton()}
</View>
</View>
<View style={styles.footer}>
<Text>List of laps</Text>
</View>
</View>
)
}
startStopButton() {
var style = this.state.isRunning ? styles.startButton : styles.stopButton;
handleStartPress = () => {
console.log('Start was pressed');
if (this.state.isRunning) {
clearInterval(this.interval);
this.setState({
isRunning: false
});
return
}
var startTime = new Date();
this.interval = setInterval(
()=>{
this.setState({
timeElapsed: new Date() - startTime
})
}, 30
);
this.setState({
isRunning: true
})
}
return (
<TouchableHighlight style={[styles.button, style]} onPress={handleStartPress} underlayColor="gray">
<Text>{this.state.isRunning ? 'Stop' : 'Start'}</Text>
</TouchableHighlight>
)
}
lapButton() {
handleLapPress = () => {
console.log('Lap was pressed');
}
return (
<TouchableHighlight style={[styles.button, styles.lapButton]} onPress={handleLapPress} underlayColor="gray">
<Text>Lap</Text>
</TouchableHighlight>
)
}
border(color) {
return {
borderColor: color,
borderWidth: 4
}
}
}
var styles = StyleSheet.create({
container: { // Main container
flex: 1,
alignItems: 'stretch'
},
header: { // Yellow
flex: 2
},
footer: { // Blue
flex: 3
},
timerWrapper: {
flex: 5,
justifyContent: 'center',
alignItems: 'center'
},
timer: {
fontSize: 60
},
buttonWrapper: {
flex: 3,
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center'
},
button: {
borderWidth: 2,
height: 100,
width: 100,
borderRadius: 50,
justifyContent: 'center',
alignItems: 'center'
},
startButton: {
borderColor: 'red'
},
stopButton: {
borderColor: 'green'
},
lapButton: {
borderColor: 'blue'
}
});
AppRegistry.registerComponent('stopwatch', () => StopWatch);
You need to bind your class methods to the correct this. See the facebook documentation on using ES6 classes: https://facebook.github.io/react/docs/reusable-components.html#es6-classes.
To fix your error, bind your methods inside of your classes constructor:
class StopWatch extends Component {
constructor(props) {
super(props);
this.state = {
timeElapsed: null,
isRunning: false
}
this.startStopButton= this.startStopButton.bind(this)
this.lapButton = this.lapButton.bind(this)
this.handleStartPress = this.handleStartPress.bind(this)
this.handleLap = this.handleLap.bind(this)
}
render() {
return (
<View style={styles.container}>
<View style={styles.header}>
<View style={styles.timerWrapper}>
<Text style={styles.timer}>{formatTime(this.state.timeElapsed)}</Text>
</View>
<View style={styles.buttonWrapper}>
{this.startStopButton()}
{this.lapButton()}
</View>
</View>
<View style={styles.footer}>
<Text>List of laps</Text>
</View>
</View>
)
}
startStopButton() {
var style = this.state.isRunning ? styles.startButton : styles.stopButton;
return (
<TouchableHighlight style={[styles.button, style]} onPress={this.handleStartPress} underlayColor="gray">
<Text>{this.state.isRunning ? 'Stop' : 'Start'}</Text>
</TouchableHighlight>
)
}
lapButton() {
return (
<TouchableHighlight style={[styles.button, styles.lapButton]} onPress={this.lapPress} underlayColor="gray">
<Text>Lap</Text>
</TouchableHighlight>
)
}
border(color) {
return {
borderColor: color,
borderWidth: 4
}
}
handleStartPress() {
console.log('Start was pressed');
if (this.state.isRunning) {
clearInterval(this.interval);
this.setState({
isRunning: false
});
return
}
var startTime = new Date();
this.interval = setInterval(
()=>{
this.setState({
timeElapsed: new Date() - startTime
})
}, 30
);
this.setState({
isRunning: true
})
}
lapPress() {
console.log('Lap was pressed');
}
}
sorry for the bad formatting
This has nothing to do with ES6, it's an inherent difficulty with the way Javascript works.
Your error is here:
onPress={this.lapPress}
You are thinking that means "when the button is pressed, invoke the method lapPress on my component". It doesn't. It means "when the button is pressed, invoke the method lapPress from my component, using whatever this happens to be set to".
There are several ways to bind this to its method properly, but the easiest (in ES6) might be
onPress={() => this.lapPress()}

Resources