How to use navigation.navigate() in map function - react-native

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/

Related

unable to print console.log in button 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

react-native 'react-native-html-to-pdf' Warning

I'm using a 'react-native-html-to-pdf' library.
I used it exactly like the example, but I get an error.
Warning
Possible Unhandled Promise Rejection(id: 0):
TypeError: Cannot read property 'convert' of undefined
TypeError: Cannot read property 'convert' of undefined
at createPDF$~~~~~~~~~~~~~~~~~~~~~~~~
https://github.com/christopherdro/react-native-html-to-pdf
import React, { Component } from 'react'
import { Text, View, Button, YellowBox, FlatList, Image, ScrollView, Dimensions, TouchableHighlight } from 'react-native'
import Swiper from 'react-native-swiper'
import {styles} from '../style/styles'
import RNHTMLtoPDF from 'react-native-html-to-pdf'
class NavtexPage extends Component {
constructor(props) {//클래스가 생성될때 제일 먼저 실행되는 함수
YellowBox.ignoreWarnings([
'Warning: componentWillReceiveProps is deprecated',
'Warning: componentWillUpdate is deprecated',
]);
super(props);
this.onPressNext = this.onPressNext.bind(this);
this.onPressPrev = this.onPressPrev.bind(this);
this.createPDF = this.createPDF.bind(this);
}
//깃허브 컴포넌트
renderPagination = (index, total, context) => {
return (
<View style={styles.paginationStyle}>
<Text style={{ color: 'grey' }}>
<Text style={styles.paginationText}>{index + 1}</Text>/{total}
</Text>
</View>
)
}
//이전
onPressPrev = () => {
const { indexPage } = this.state;
if (indexPage > 0) {
this.refs.swiper.scrollBy(-1);
}
}
//다음
onPressNext = () => {
const { indexPage } = this.state;
// Probably best set as a constant somewhere vs a hardcoded 5
if (indexPage < 4) {
this.refs.swiper.scrollBy(1);
}
}
async createPDF() {//pdf libray
let options = {
html: '<h1>PDF TEST</h1>',
fileName: 'test',
directory: './data/',
};
console.log('pdf' + options)
let file = await RNHTMLtoPDF.convert(options)
// console.log(file.filePath);
alert(file.filePath);
}
//시작
render() {
return (
<View style={styles.container}>
<View style={{ flex: 0.1, backgroundColor: 'green' }}>
<Text>NAVTEX</Text>
</View>
{/* {깃허브 컴포넌트} */}
<Swiper
style={styles.wrapper}
onIndexChanged={indexPage => this.setState({ indexPage })}
renderPagination={this.renderPagination}
showsButtons={false}
loop={false}
ref={'swiper'}
>
<View style={styles.slide}>
<FlatList
style={{ flex: 1, marginTop: 50, borderWidth: 1, borderColor: 'red' }}
data={this.state.data}
numColumns={1}
renderItem={this._renderItem}
keyExtractor={(item, index) => item.no.toString()}/>
</View>
<View style={styles.slide}>
<Text style={styles.text}>2</Text>
</View>
<View style={styles.slide}>
<Text style={styles.text}>3</Text>
</View>
<View style={styles.slide}>
<Text style={styles.text}>4</Text>
</View>
<View style={styles.slide}>
<Text style={styles.text}>5</Text>
<TouchableHighlight onPress={this.createPDF}>
<Text>Create PDF</Text>
</TouchableHighlight >
</View>
</Swiper>
<View style={styles.buttoncontainer}>
<Button
style={{ with: 75 }}
onPress={this.onPressPrev}
title="Previous">
</Button>
<Button
onPress={this.onPressNext}
title="Next">
</Button>
</View>
</View>
);
}
}
Its just simple Link error
Link your npm :
react-native link react-native-html-to-pdf
Android All Set & in IOS you need to install POD
cd ios, pod install
Error Solved
I had this issue when linking had failed.
Make sure xcode is not running and try "react-native link react-native-html-to-pdf" again (and pod install if you are using pods). If this fails, follow the github manual linking process:
https://github.com/christopherdro/react-native-html-to-pdf#option-2-manual

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

Missing styles for item in React Native Side Menu (should indicate active route in React Native Navigator)

I'm working on an app with a Side Menu and a Navigator. In the side menu there are menu-items which let's you navigate (using Navigator), and the menu-items also get styled to indicate which one is active.
When first going to a new route with navigator.push() and then going back with navigator.pop(), the menu-item corresponding to the previously active route (which is now inactive) does not get either of the styles to show that it is either inactive or active. The style of the menu item (RouteMenuItem in the full example below) is as follows
style={[
{ padding: 15, borderColor: 'firebrick', borderWidth: 1 },
(isActive
? {backgroundColor: 'green'}
: {opacity: 0.5}
)
]}
How is it possible that neither {backgroundColor: 'green'} nor {opacity: 0.5} gets applied?
The image below shows how the bug looks on Android: "Route ONE" is selected, however, the menu item for "Route TWO" does not have opacity: 0.5 as it should (it should be half transparent like the 3rd menu item).
Below is the full code for a minimal example to reproduce the bug. The component hierarchy is like this:
<Navigator renderScene={() => <SideMenu><View /></SideMenu>} />
PS: We use StyleSheet.create() in our code, but in the example below I've just defined the styles inline. It does not seem to make any difference.
import React from 'react';
import {View, Text, TouchableHighlight, Navigator, Dimensions} from 'react-native';
import SideMenu from 'react-native-side-menu';
/***************
/** Routes **/
/****************/
const ROUTES = {
ONE: () => ({ title: 'Route ONE' }),
TWO: () => ({ title: 'Route TWO' }),
THREE: () => ({ title: 'Route THREE' }),
};
/**************/
/** Main **/
/**************/
export default class Main extends React.Component {
render() {
return (
<Navigator
style={{flex: 1}}
initialRouteStack={[
ROUTES.ONE(),
]}
renderScene={(route, navigator) =>
<Scene route={route} navigator={navigator} />
}
/>
);
}
}
/***************/
/** Scene **/
/***************/
class Scene extends React.Component {
state = {
menuIsOpen: false,
}
openMenu = () => {
this.setState({ menuIsOpen: true });
}
onMenuOpenChanged = (menuIsOpen) => {
if (this.state.menuIsOpen !== menuIsOpen) {
this.setState({ menuIsOpen });
}
}
render() {
const {route, navigator} = this.props;
return (
<View style={{flex: 1}}>
<SideMenu
menu={
<Menu
route={route}
navigator={navigator}
/>
}
menuPosition="right"
bounceBackOnOverdraw={false}
onChange={this.onMenuOpenChanged}
isOpen={this.state.menuIsOpen}
openMenuOffset={Dimensions.get('window').width * 0.75}
disableGestures={false}
>
<Screen route={route} navigator={navigator} openMenu={this.openMenu} menuIsOpen={this.state.menuIsOpen} />
</SideMenu>
</View>
);
}
}
/**************/
/** Menu **/
/**************/
class Menu extends React.Component {
render() {
const {route, navigator} = this.props;
return (
<View style={{ flex: 1, backgroundColor: 'coral', paddingTop: 25 }}>
<Text>Currently at {route.title}</Text>
<RouteMenuItem forRoute={ROUTES.ONE()} route={route} navigator={navigator} />
<RouteMenuItem forRoute={ROUTES.TWO()} route={route} navigator={navigator} />
<RouteMenuItem forRoute={ROUTES.THREE()} route={route} navigator={navigator} />
</View>
);
}
}
const RouteMenuItem = ({forRoute, route, navigator}) => (
<TouchableHighlight onPress={() => navigator.push(forRoute)}>
<Text style={[ { padding: 15, borderColor: 'firebrick', borderWidth: 1 }, (forRoute.title === route.title ? {backgroundColor: 'green'} : {opacity: 0.5}) ]}>
Go to {forRoute.title} ({(forRoute.title === route.title ? 'current route' : 'NOT CURRENT ROUTE')})
</Text>
</TouchableHighlight>
);
/*****************************/
/** Screen, inside Menu **/
/*****************************/
class Screen extends React.Component {
render() {
const {route, navigator, openMenu, menuIsOpen} = this.props;
return (
<View style={{ flex: 1 }}>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', backgroundColor: 'peachpuff', paddingTop: 25 }}>
<HeaderButton onPress={navigator.pop}>Back</HeaderButton>
<HeaderButton onPress={openMenu}>Menu</HeaderButton>
</View>
<View style={{ flex: 1, backgroundColor: 'white' }}>
<Text style={{ margin: 50, fontSize: 50 }}>
{route.title}
</Text>
</View>
</View>
);
}
}
const HeaderButton = ({onPress, children}) => (
<TouchableHighlight underlayColor="green" onPress={onPress}>
<Text style={{ padding: 10, borderColor: 'firebrick', borderWidth: 1 }}>
{children}
</Text>
</TouchableHighlight>
);
The problem occurs becauase children of TouchableHighlight gets default opacity (1) after the TouchableHighlight is pressed. As that is a more specific problem I've asked a new question here.
In this case the bug appears when going back to a previous route, because the menu item in that instance of the Menu was pressed (moving us to a new route before we could spot the bug).