unable to print console.log in button react-native - react-native

i have created a custom button component for reuseability here is my button code
export default function AppButton({ title, color = "", marginVertical = 0 }) {
return (
<TouchableHighlight
style={[
styles.button,
{ backgroundColor: colors[color], marginVertical: marginVertical }]}
>
<Text style={styles.text}>{title}</Text>
</TouchableHighlight>
);
}
here is my button in which I want to print console .log
<AppButton
title="login"
onPress={() => console.log("email and password recieved")}
/>

Try this, you need to pass the onpress function as props to touchable highlight.
export default function AppButton({ title, color = "", marginVertical = 0 }) {
return (
<TouchableHighlight
onPress={onClick}
style={[
styles.button,
{ backgroundColor: colors[color], marginVertical: marginVertical },
]}
>
<Text style={styles.text}>{title}</Text>
</TouchableHighlight>
);
}
<AppButton
title="login"
onClick={() => console.log("email and password recieved")}
/>
More details can be found in the docs: https://reactnative.dev/docs/touchablehighlight

Related

How to use navigation.navigate() in map function

I'm trying to display a list of TouchableOpacity to navigate to an other page with navigation.navigate(...).
I'm using map to display the list but I can't navigate, the onPress don't work with this error message : "undefined is not an object (evaluating 'navigation.navigate')
What am I doing wrong ?
function PopupMenuAction ({navigation}) {
return (
<>
<TouchableOpacity style={style.shape1to2} onPress={() => resizeBox(1)}>
<Text style={style.subtext}>Add <Text style={{ color: layouts.secondary }}>+</Text></Text>
</TouchableOpacity>
<Modal transparent visible={visible}>
<SafeAreaView style={{ flex: 1 }} onTouchStart={() => resizeBox(0)}>
<Animated.View
style={[
style.popUp,
{ opacity: scale.interpolate({ inputRange: [0, 1], outputRange:[0, 1]}) },
{ transform: [{ scale }]},
]}
>
{/* THERE IS THE CODE WHERE IT DONT WORK
=>>>*/}
{actions.map((op, i) => (
<TouchableOpacity style={[
style.option,
{ borderBottomWidth: i === actions.length - 1 ? 0 : 1 }]}
key={i}
onPress={() => navigation.navigate('CreateReaction')}
>
<Text style={{ fontFamily: "Title-Font", fontSize: 15 }}>{op.title}</Text>
</TouchableOpacity>
))}
</Animated.View>
</SafeAreaView>
</Modal>
</>
)
}
Believe navigation does not exist in your functional components because the error indicates it is undefined.
Try to import the useNavigation() hook from react-navigation library and use the returned navigate function.
import { useNavigation } from '#react-navigation/native';
function PopupMenuAction ({navigation}) {
const { navigate } = useNavigation()
return (
// rest of your code
)
docs: https://reactnavigation.org/docs/use-navigation/

passing data into a modal

I'm trying to pass some data from container to modal, and i've done this. it got error undefined is not an object evaluating (evaluating _this.props.status) is there anything i did worng? what should i call in props
these are my codes
container.js
buildPanel(index, item) {
let panel = [];
let keys = DBkeys['Requests'].MyRequest;
let status = item[keys['status']];
panel.push(<View style={{ position: 'absolute', right: 0, bottom: 0, padding: normalize(5), alignItems: 'center' }} key={'status'}>
<TouchableOpacity onPress={this.handleShowModal()}>
<Icon name={img.itemStatus[status].name} type={img.itemStatus[status].type} color={img.itemStatus[status].color} size={normalize(38)} />
</TouchableOpacity>
</View>);
return panel;
}
<View style={[styles.panelContainer, status === 'success' ? {} : { backgroundColor: color.white }]}>
<FlatList
showsVerticalScrollIndicator={false}
progressViewOffset={-10}
refreshing={this.state.refreshing}
onRefresh={this.onRefresh.bind(this)}
onMomentumScrollEnd={(event) => event.nativeEvent.contentOffset.y === 0 ? this.onRefresh() : null}
data={content}
renderItem={({ item }) => item}
keyExtractor={(item, key) => key.toString()}
/>
</View>
<IconModal visible={this.state.modalVisible} close={this.handleDismissModal} status='test' desc='test' />
IconModal.js
const IconModal = (props) => {
return(
<Modal
isVisible={props.visible}
onBackdropPress={props.close}
>
<View style={styles.dialogBox}>
<View style={styles.icon}>
<Icon></Icon>
</View>
<View style={styles.text}>
<Text style={styles.status}>{this.props.status}</Text>
<Text>{this.props.desc}</Text>
</View>
<TouchableOpacity onPress={props.close}>
<View>
<Text style={styles.buttonText}>GOT IT</Text>
</View>
</TouchableOpacity>
</View>
</Modal>
)
}
IconModal.propTypes ={
visible: PropTypes.bool.isRequired,
close: PropTypes.func,
}
Use double quotes while passing string to the component. like status="test" desc="test" instead of status='test' desc='test' . and instead of this.props.status use props.status. same with this.props.desc
Remove the this keyword. It should be just props.status and props.desc

Set a TouchableHighlight near CustomDrawer with React Native

I want to set my simple TouchableHighlight just near my CustomDrawer but i can't find how to do it . Here is the code .
class App extends Component {
render() {
return (
<View style={{ flex: 1, flexDirection: 'row',marginTop: (Platform.OS
=== "ios") ? 20 : 0 }} >
<View style={styles.container}>
<TouchableHighlight onPress={this._onPressButton}>
<Image
style={styles.button}
source={require('./camera.png')}
/>
</TouchableHighlight>
</View>
<CustomDrawer
content={<NavigationMenu />}
ref="drawerSideMenu"
onClose={() => { this.props.dispatch(navigationMenuStatus(false)); }}
onOpen={() => { this.props.dispatch(navigationMenuStatus(true)) }}>
<HeaderBar />
</View>
);
}
}
const styles = StyleSheet.create({
button: {
padding: 6,
height:50,
width:50
},
countContainer: {
},
countText: {
color: '#FF00FF'
}
})
export default Appp
Actually i get this as interface but i want to make the button Camera in the blue area near the icon of menu
Any help please ?
Try inserting the camera icon inside the menu bar.
something like this
<View style={styles.container}>
<View style={styles.menuBar}>
<Icon/>
<Menu/>
</View>
</View>

React Native TouchableHighlight not working with Sectionlist

I've got a SectionList, and for every row in the list I want to be able to detect a click event.
renderList() {
if (this.state.searching) {
return (
<SectionList
sections={this.state.data}
renderSectionHeader={this.props.renderSectionHeader}
renderItem={this.props.renderItem}
/>
);
}
return null;
}
render() {
return (
<View style={styles.container}>
<Animated.View
style={{ opacity: 1 - this.state.backgroundColor }}
pointerEvents={this.state.searching ? 'none' : undefined}
>
{this.props.children}
</Animated.View>
<Animated.View
style={[
styles.backgroundColorView,
{ opacity: this.state.backgroundColor },
]}
/>
<Animated.View
style={[styles.searchResults, { top: this.state.yPos }]}
>
<TextInput
ref={(input) => { this.searchBar = input; }}
style={styles.textInput}
value={this.props.query}
onChangeText={this.onChangeText}
maxLength={100}
placeholder={this.props.placeholder}
onFocus={this.onFocus}
onBlur={this.onUnSearch}
/>
{this.renderList()}
</Animated.View>
</View>
);
For my renderItem method, I'm passing in the following PureComponent, which is just a Text contained in a TouchableHighlight.
class SubjectSearchItem extends React.PureComponent {
render() {
const item = this.props.item;
return (
<TouchableHighlight
onPress={() => console.log(item)}
>
<View style={{
marginHorizontal: 20,
marginVertical: 10,
}}
>
<Text>{`${item.item.long_name} (${item.item.short_name})`}</Text>
</View>
</TouchableHighlight>
);
}
}
and here's the renderItem prop I'm passing in
const renderItem = item => (
<SubjectSearchItem
item={item}
/>
);
The problem is, no click events are being detected. The row isn't getting highlighted, and the onPress isn't being fired. Any ideas?
Note: seems like this has been an issue for a little while

Modal View in React Native

I am new to react native, I am trying to present a view modally. I have a table view and when one of the rows is clicked I want the view to show up modally.
This is how I am implementing the transition right now :
renderbooks(books) {
return (
<TouchableHighlight onPress={() => this.showbooksDetail(books)} underlayColor='#dddddd'>
<View>
<View style={styles.container}>
<View style={styles.rightContainer}>
<Text style={styles.title}>{books.title}</Text>
</View>
</View>
<View style={styles.separator} />
</View>
</TouchableHighlight>
);
}
showbooksDetail(books){
this.props.navigator.push({
title:books.title,
component: ProductView,
passProps:{books}
});
}
How can I modify this so that the view can be presented modally?
FYI: I have already looked at multiple questions and sample projects such as these:
How do I create a native looking modal view segue with react-native?
http://facebook.github.io/react-native/docs/modal.html#content
https://github.com/aaronksaunders/React-Modal-Nav-Example
Check out the built-in Modal. It's implemented on iOS, Android implementation should come in one of the next releases of React Native.
The documentation contains an example on how to use it.
In your case it would be something like:
renderBooks(books) {
...
<Modal
animated={true}
transparent={true}
visible={!!this.state.selectedBook}>
<Text>{this.state.selectedBook.title}</Text>
</Modal>
...
}
showDetail(book) {
this.setState({
selectedBook: book,
});
}
Check this simple and powerful small library react-native-modal-animated, simply install it by yarn add react-native-modal-animated, or npm install react-native-modal-animated.
import { AnimatedModal } from 'react-native-modal-animated
<View style={styles.container}>
<TouchableOpacity
onPress={() => {
this.setState({ modalVisible: true });
alert
}}
style={styles.button}
>
<Text style={styles.buttonText}>Show Modal</Text>
</TouchableOpacity>
<AnimatedModal
visible={this.state.modalVisible}
onBackdropPress={() => {
this.setState({ modalVisible: false });
}}
animationType="vertical"
duration={600}
>
{/*Any child can be used here */}
<View style={styles.modalCard}>
<Text>I'm AnimatedModal</Text>
<Text style={{fontWeight: 'bold', marginTop: 10}}>vertical</Text>
</View>
</AnimatedModal>
</View>
);
}
}
I am using the react-native modalbox. Its been awesome you get modals to be displayed in top,center,bottom,etc.Check the below link once:https://github.com/maxs15/react-native-modalbox
Sample:
import React from 'react';
import Modal from 'react-native-modalbox';
import Button from 'react-native-button';
import {
AppRegistry,
Text,
StyleSheet,
ScrollView,
View,
Dimensions
} from 'react-native';
class Example extends React.Component {
constructor() {
super();
this.state = {
isOpen: false,
isDisabled: false,
swipeToClose: true,
sliderValue: 0.3
};
}
onClose() {
console.log('Modal just closed');
}
onOpen() {
console.log('Modal just openned');
}
onClosingState(state) {
console.log('the open/close of the swipeToClose just changed');
}
render() {
return (
<View style={styles.wrapper}>
<Button onPress={() => this.refs.modal1.open()} style={styles.btn}>Basic modal</Button>
<Button onPress={() => this.refs.modal2.open()} style={styles.btn}>Position top</Button>
<Button onPress={() => this.refs.modal3.open()} style={styles.btn}>Position centered + backdrop + disable</Button>
<Button onPress={() => this.refs.modal4.open()} style={styles.btn}>Position bottom + backdrop + slider</Button>
<Modal
style={[styles.modal, styles.modal1]}
ref={"modal1"}
swipeToClose={this.state.swipeToClose}
onClosed={this.onClose}
onOpened={this.onOpen}
onClosingState={this.onClosingState}>
<Text style={styles.text}>Basic modal</Text>
<Button onPress={() => this.setState({swipeToClose: !this.state.swipeToClose})} style={styles.btn}>Disable swipeToClose({this.state.swipeToClose ? "true" : "false"})</Button>
</Modal>
<Modal style={[styles.modal, styles.modal2]} backdrop={false} position={"top"} ref={"modal2"}>
<Text style={[styles.text, {color: "white"}]}>Modal on top</Text>
</Modal>
<Modal style={[styles.modal, styles.modal3]} position={"center"} ref={"modal3"} isDisabled={this.state.isDisabled}>
<Text style={styles.text}>Modal centered</Text>
<Button onPress={() => this.setState({isDisabled: !this.state.isDisabled})} style={styles.btn}>Disable ({this.state.isDisabled ? "true" : "false"})</Button>
</Modal>
<Modal style={[styles.modal, styles.modal4]} position={"bottom"} ref={"modal4"}>
<Text style={styles.text}>Modal on bottom with backdrop</Text>
</Modal>
</View>
);
}
}
const styles = StyleSheet.create({
modal: {
justifyContent: 'center',
alignItems: 'center'
},
modal2: {
height: 230,
backgroundColor: "#3B5998"
},
modal3: {
height: 300,
width: 300
},
modal4: {
height: 300
},
wrapper: {
paddingTop: 50,
flex: 1
},
});
AppRegistry.registerComponent('Example', () => Example);