Is there a way to make an onpress navigation inside a result of a array map in react-native? - react-native

I have a simple array of names in this.state.members. I used the map function to iterate the members.
I want to add a button for each member so, when i click to them, i go to a screen dedicated to each member.
I test the button outise the loop, it is working.
But for those inside the map function, its says "undefined is not an object (evaluating '_this2.props.navigation')
onPress"
i spent a whole day trying to understand what is going on without any luck.
Any help will be appreciated.
Here is my code
import { StyleSheet, Text, View } from "react-native";
import { ListItem, Button } from "react-native-elements";
export default class ProfileScreen extends React.Component {
static navigationOptions = {
header: null
};
constructor(props) {
super(props);
this.state = {
members: ["Allie", "Gator", "Lizzie"],
id_groupe: "",
groupe: ""
};
// this.handleSubmit = this.handleSubmit.bind(this);
}
render() {
const members = this.state.members;
const namesList = members.map(function(name, i) {
return (
<Button
onPress={() => this.props.navigation.navigate("Home")}
title={name}
key={i}
/>
);
});
return (
<View style={styles.container}>
<View>{namesList}</View>
<View>
<Button
title="Back to home"
onPress={() => this.props.navigation.navigate("Home")}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center"
}
});

just use an arrow function, and you will not have the this issue. But not sure about your actual problem, if the arrow function works let's check if you have any other issue.
Arrow function when you iterate with map:
const namesList = members.map((name, i) => {
return (
<Button
onPress={() => this.props.navigation.navigate("Home")}
title={name}
key={i}
/>
);
});

Related

setAccessibilityFocus using ref not working

I'm using the ref prop along with findNodeHandle on a bunch of components in order to be able to trigger AccessibilityInfo.setAccessibilityFocus. However, it's not always working as expected. Sometimes the reference is null even though componentDidMount has executed.
I'm often using setAccessibilityFocus in order to focus the header of a new element which appears on the screen, for example when opening a modal.
IMPORTANT: This is Voiceover/Talkback functionality so you'll need to have that activated on your device.
See my snack: https://snack.expo.io/#insats/example-accessibilityinfo-setaccessibilityfocus-not-working
This is the code sample:
import React, { Component } from 'react';
import {
View,
Text,
findNodeHandle,
TouchableOpacity,
AccessibilityInfo,
StatusBar,
} from 'react-native';
class Sample extends React.Component {
constructor(props) {
super(props);
this.accessibilityRef = null;
}
componentDidMount() {
console.log('componentDidMount');
this.setAccessibilityFocus();
}
setAccessibilityRef(el) {
console.log('setAccessibilityRef', el);
this.accessibilityRef = el;
}
setAccessibilityFocus() {
console.log('setAccessibilityFocus', this.accessibilityRef);
if (this.accessibilityRef) {
const reactTag = findNodeHandle(this.accessibilityRef);
AccessibilityInfo.setAccessibilityFocus(reactTag);
}
}
render() {
console.log('Rendering Sample');
return (
<Text ref={this.setAccessibilityRef}>
This text ought to be read out loud by the screenreader if enabled
</Text>
);
}
}
export default class App extends React.Component {
state = {
open: false,
};
toggle = () => this.setState({ open: !this.state.open });
render() {
return (
<View style={{ margin: 50 }}>
<StatusBar hidden />
<TouchableOpacity
style={{ backgroundColor: 'blue', padding: 20, marginBottom: 20 }}
onPress={this.toggle}>
<Text style={{ color: 'white' }}>
{this.state.open ? 'Hide text' : 'Show text'}
</Text>
</TouchableOpacity>
{this.state.open && <Sample />}
</View>
);
}
}
I don't really understand what is causing these issues. I've found that calling the setAccessibilityFocus twice solves the problem. You can simplify the logic of focusing by just handling everything in the callback ref as well.
Example:
export default () => {
const setInitFocus = (element: React.Component | null) => {
if (element == null) return;
const elementId = findNodeHandle(element);
if (elementId) {
AccessibilityInfo.setAccessibilityFocus(elementId);
AccessibilityInfo.setAccessibilityFocus(elementId);
}
};
return (
<TouchableOpacity
onPress={() => {}}
ref={setInitFocus}
>
<Text>Blah blah</Text>
</TouchableOpacity>
);
};
Here's your snack with those changes applied:
https://snack.expo.io/#loganlim/example-accessibilityinfo-setaccessibilityfocus-not-working

React-Native: Setting focus to custom component built off an array

I am trying to create a list of custom inputs based on an array, and when pressing the the enter key, I'd like the focus to automatically move to the next custom input. I can get this to work with a regular <TextInput> react component using the ref and onSubmitEditing but I cannot get this to function properly using my custom component that wraps a <TextInput>
Here is my code, it consists of two files: App.js and TextInput2.js (I know that currently the last line will error because of the reference counter but if I can get it to work I'll address the last issue)
Working Snack
-- App.js --
import React from 'react';
import { StyleSheet, View, TextInput } from 'react-native';
import TextInput2 from './TextInput2'
export default class App extends React.Component {
constructor(){
super();
this.myRef = [];
this.state = {}
}
focusField = (key) => {
this.myRef[key].focus()
}
render() {
let textFields = ["one", "two", "three", "four", "five"];
return (
<View style={styles.container}>
{
textFields.map((x, i) => {
this.myRef[i] = React.createRef();
let k = i + 1
return(
<TextInput2
name={x}
key={i}
placeholder={x + " This Doesnt Work"}
ref={ref => this.myRef[i] = ref}
nextRef={this.myRef[k]}
//onSubmitEditing={() => this.focusField(k)}
//onSubmitEditing={() => this.myRef[k].focus()}
blurOnSubmit={false}
/>
)
})
}
{
textFields.map((x, i) => {
this.myRef[i] = React.createRef();
return(
<TextInput
name={x}
key={i}
placeholder="This works!"
ref={ref => this.myRef[i] = ref}
onSubmitEditing={() => this.focusField(i+1)}
blurOnSubmit={false}
/>
)
})
}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});
--TextInput2.js --
import React from 'react';
import { View, TextInput } from 'react-native';
export default class TextInput2 extends React.Component {
state={}
handleFocus = () => {}
handleBlur = () => {}
focus() {
this.props.nextRef.focus()
}
render() {
return (
<View >
<TextInput
{...this.props}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
onSubmitEditing={() => this.focus()}
/>
</View>
)
}
}
I've read this post and this but cannot seem to determine how to setup the function to set focus on the next field.
I have edited the Snack. Please try this
I think you're making it complicated. Try to change like this,
this.myRef[index] = React.createRef()
CustomTextComponent component
<CustomTextComponent
name={Something}
key={index}
forwardRef={this.myRef[index]}
onSubmitEditing={() => this.myRef[index + 1].current.focus()}
/>
As you're using createRef() you have to call it's ref using the "current" object.
CustomComponent.js
import React from 'react';
import { View, TextInput } from 'react-native';
export default class CustomComponent extends React.Component {
render() {
return (
<View >
<TextInput
{...this.props}
returnKeyType={"next"}
ref={this.props.forwardRef}
onSubmitEditing={this.props.onSubmitEditing}
/>
</View>
)
}
}

Better solution to open the Menu when 3 dots are clicked in React Native

I am able to open menu when 3 dots icon is clicked for each item. But can the code be written in a better way..
Right now menu is getting created for each card item but ideally it would have been good to create single Menu View and dynamically associate it to some card where ever the 3 dots is clicked.
Expo Source Code Link
Code
export default class App extends React.Component {
constructor(props, ctx) {
super(props, ctx);
this.state = {
list: [
{ name: "Michael", mobile: "9292929292", ref: React.createRef() },
{ name: "Mason Laon Roah", mobile: "1232313233", ref: React.createRef() },
{ name: "Constructor", mobile: "4949494949", ref: React.createRef() },
{ name: "Rosling", mobile: "4874124584", ref: React.createRef() }
],
};
}
_menu = null;
hideMenu = () => {
this._menu.hide();
};
showMenu = (ref) => {
this._menu = ref;
this._menu.show();
};
render() {
const renderItem = ({ item, index }) => (
<ListItem
title={
<View>
<Text style={{ fontWeight: "bold" }}>{item.name}</Text>
<Text>{item.mobile}</Text>
</View>
}
subtitle={
<View>
<Text>445 Mount Eden Road, Mount Eden, Auckland. </Text>
<Text>Contact No: 134695584</Text>
</View>
}
leftAvatar={{ title: 'MD' }}
rightContentContainerStyle={{ alignSelf: 'flex-start'}}
rightTitle={this.getMenuView(item.ref)}
/>
);
return (
<View style={styles.container}>
<View style={{ flex: 1, marginTop: 30 }}>
<FlatList
showsVerticalScrollIndicator={false}
keyExtractor={(item, index) => index.toString()}
data={this.state.list || null}
renderItem={renderItem}
ItemSeparatorComponent={() => (
<View style={{ marginBottom: 5 }} />
)}
/>
</View>
</View>
);
}
getMenuView(ref) {
return (
<Menu
ref={ref}
button={<Icon onPress={() => this.showMenu(ref.current)} type="material" color="red" name="more-vert" />}
>
<MenuItem onPress={this.hideMenu}>Menu item 1</MenuItem>
<MenuItem onPress={this.hideMenu}>Menu item 2</MenuItem>
<MenuItem onPress={this.hideMenu} disabled>
Menu item 3
</MenuItem>
<MenuDivider />
<MenuItem onPress={this.hideMenu}>Menu item 4</MenuItem>
</Menu>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
});
Sample Output
As mentioned here, you can find an undocumented UIManager.java class that allows you to create Popups with its showPopupMenu method.
This currently works only for Android.
import React, { Component } from 'react'
import { View, UIManager, findNodeHandle, TouchableOpacity } from 'react-native'
import Icon from 'react-native-vector-icons/MaterialIcons'
const ICON_SIZE = 24
export default class PopupMenu extends Component {
constructor (props) {
super(props)
this.state = {
icon: null
}
}
onError () {
console.log('Popup Error')
}
onPress = () => {
if (this.state.icon) {
UIManager.showPopupMenu(
findNodeHandle(this.state.icon),
this.props.actions,
this.onError,
this.props.onPress
)
}
}
render () {
return (
<View>
<TouchableOpacity onPress={this.onPress}>
<Icon
name='more-vert'
size={ICON_SIZE}
color={'grey'}
ref={this.onRef} />
</TouchableOpacity>
</View>
)
}
onRef = icon => {
if (!this.state.icon) {
this.setState({icon})
}
}
}
Then use it as follows.
render () {
return (
<View>
<PopupMenu actions={['Edit', 'Remove']} onPress={this.onPopupEvent} />
</View>
)
}
onPopupEvent = (eventName, index) => {
if (eventName !== 'itemSelected') return
if (index === 0) this.onEdit()
else this.onRemove()
}
Source: https://cmichel.io/how-to-create-a-more-popup-menu-in-react-native
There is now a React Native plugin for this. I'm not sure it was around when the question was originally asked. But I'm leaving this here for anyone else looking for the answer.
https://www.npmjs.com/package/react-native-popup-menu
The example worked for me. I wanted to use the vertical ellipsis, so I did this modification to the MenuTrigger part of the example to an icon instead of text:
<MenuTrigger>
<Icon name="more-vert" size={25} color={colors.rustRed} />
</MenuTrigger>
As a side note, I had difficulty finding and using the ellipsis. I eventually went with using react-native-vector-icons by using 'npm -i react-native-vector-icons' and importing the Material Icons like this:
import Icon from 'react-native-vector-icons/MaterialIcons';
Use React Portals
https://reactjs.org/docs/portals.html
In short the receipts is:
You define your dynamic menu at sibling level only once in the parent i.e. in your case it would be adjacent to App.
Handle Click at each item level to open your component. You can pass some specific event days to achieve the dynamism.
Easier example https://codeburst.io/reacts-portals-in-3-minutes-9b2efb74e9a9
This achieves exactly what you are trying to do which is defer the creation of component untill clicked.

State does not change until the second button press? Adding a call back throws an error "invariant violation: invalid argument passed"

I'm trying to render a Flatlist that contains a store name. Upon clicking the store name, more information about the store should be displayed.
I attempted to change state and then use
{this.renderMoreDetails(item) && this.state.moreDetailsShown}
to get the additional information to appear. However, it was clear via console.log that state was only changed after a second button press.
From what I read in this article 1 and this article 2 it seemed as though I needed a callback function as an additional parameter to my setState().
I tried adding a callback function(probably incorrect, but I'm extremely lost at this point) and only got more errors.
I know that I have access to all of the data from renderItem inside FlatList. How do I make it appear upon click?
import React, { Component } from 'react';
import {
View,
FlatList,
Text,
TouchableWithoutFeedback,
ListView,
ScrollView
} from 'react-native'
import { NavigationActions } from 'react-navigation';
import { Header, Card, CardSection } from '../common';
import Config from '../Config';
export default class Costco extends Component<Props> {
constructor(props) {
super(props);
this.state = {
stores: [],
selectedItem: {id: null},
};
}
componentWillMount() {
const obj = Config.costcoThree;
const costcoArr = Object.values(obj);
this.setState({
stores: costcoArr,
})
}
renderListOfStores() {
return <FlatList
data={this.state.stores}
renderItem={ ({item}) => this.singleStore(item)}
keyExtractor={(item) => item.id}
extraData={this.state.selectedItem} />
}
singleStore(item) {
console.log(this.state.selectedItem.id)
return item.id === this.state.selectedItem.id ?
<TouchableWithoutFeedback
onPress={() => this.selectStore(item)}
>
<View>
<Text>{item.branchName}</Text>
<Text>Opening Time {item.openingTime}</Text>
<Text>Closing Time {item.closingTime}</Text>
<Text>Address {item.dongAddKor}</Text>
</View>
</TouchableWithoutFeedback>
:
<TouchableWithoutFeedback>
<View>
<Text>{item.branchName}</Text>
<Text>Only showing second part</Text>
</View>
</TouchableWithoutFeedback>
}
selectStore(item) {
this.setState({selectedItem: item});
console.log('repssed');
}
render() {
return(
<ScrollView>
<Header headerText="Costco"/>
<Text>hello</Text>
{this.renderListOfStores()}
</ScrollView>
)
}
}
as a workaround you can have a state that maintain your selected item to expand(or something like another view) and then you can use some conditions to work for render your flat list data.
Consider the below code and let me know if you need some more clarification.
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,FlatList,TouchableNativeFeedback,
View
} from 'react-native';
export default class App extends Component<Props> {
constructor(props) {
super(props);
this.state = {
response: [],
selectedItem: {id: null},
};
}
userListLayout() {
const {response} = this.state;
return <FlatList data={response} renderItem={ ({item}) => this.singleUserLayout(item)} keyExtractor={(item) => item.email} extraData={this.state.selectedItem} />
}
singleUserLayout(item) {
return item.id == this.state.selectedItem.id ?
<TouchableNativeFeedback onPress={() => this.userSelected(item)}>
<View style={{flex:1, borderColor: 'black', borderWidth: 1}}>
<Text style={{padding: 10, fontSize: 25}}>{item.email}</Text>
<Text style={{padding: 10,fontSize: 20}}>{item.name}</Text>
</View>
</TouchableNativeFeedback>
: <TouchableNativeFeedback onPress={() => this.userSelected(item)}><Text style={{padding: 10,fontSize: 20}}>{item.email}</Text></TouchableNativeFeedback>
}
userSelected(item) {
console.log(item)
this.setState({selectedItem: item})
}
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/users")
.then(data => data.json())
.then(response => this.setState({response}))
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>HI THERE</Text>
{this.userListLayout()}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});

In React-native, how to handle checkbox in Listview?

In my react-native app, I am trying to show my contact details with checkboxes for selecting.
Here is my code:
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData, sectionID, rowID) => (
<TouchableHighlight onPress={() => this.goRideDetails(rowData)}>
<Text style={styles.rideHeader}>{rowData.name} </Text>
<CheckBox
checked={this.state.checked}
onCheckBoxPressed={() =>
this.setState({ checked: !this.state.checked })
}
/>
</TouchableHighlight>
)}
/>
In my view checkbox is displaying on every row, but not working.
Any one can help me. Thanks in advance.
You can easily do this with component separation. Please, take a look here:
export default class ContactList extends Component {
static propTypes = {
contacts: React.PropTypes.array,
}
static defaultProps = {
contacts: [],
}
constructor(){
super();
this._renderRow = this._renderRow.bind(this);
}
_renderRow(rowData,sectionID,rowID) {
return <Contact info={ rowData } />;
}
render() {
return (
<ListView
dataSource={ this.props.contacts }
renderRow={ this._renderRow }
/>
);
}
}
export class ContactList extends Component {
static propTypes = {
info: React.PropTypes.object.isRequired,
}
constructor(){
super();
this.goRideDetails = this.goRideDetails.bind(this);
this.setChecked = this.setChecked.bind(this);
}
goRideDetails() {
//your logic here
}
setChecked() {
this.props.info.checked = !this.props.info.checked; //will be much better to do it with redux and action creators
}
render() {
return (
<TouchableHighlight onPress={ this.goRideDetails }>
<Text style={ styles.rideHeader }>{this.props.info.name} </Text>
<CheckBox checked={ this.props.info.checked } onCheckBoxPressed={ this.setChecked } />
</TouchableHighlight>
);
}
}
After that you can simply call:
<ContactList contacts={this.state.dataSource} />
in your jsx and voila.
Important note: Do not use array functions inside your jsx code blocks.
Important note 2: Try to start using redux or flux for storing state of your application. It will be provide much better code design.
Hope, it will help.
import React , {Component} from 'react'
import {
Text,
View,
ListView,
StyleSheet,
TouchableOpacity,
Image,
} from 'react-native'
import CheckBox from 'react-native-checkbox'
var Folder = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2})
var folder = '' ////// all the new folder
var check_folder = [] ////// all the check box conditions
class ApproveContent extends Component {
///////// all the upper thing that are global variable for this script is has same value as that of the state the only reason we are using this because of the layout update //////////
state={
folder:[],
data:[],
check:[]/////// this need to do just to upadte the layout of the check box
}
render(){
return(
<View style = {{flex:1,backgroundColor:'white',alignItems:'center'}}>
<ListView
dataSource={Folder.cloneWithRows(this.state.folder)}
renderRow={(rowData,rowID,sectionID) => <View style = {{ alignItems: 'center',margin:5}}>
<TouchableOpacity style = {{width:Dimension.ScreenWidth/1.2,height:Dimension.ScreenHeight/6,flexDirection: 'row',alignItems:'center'}}
onPress={() => {}}>
<CheckBox
label=''
labelBefore={false}
checked={this.state.check[sectionID]}
checkboxStyle = {{marginLeft: 20}}
onChange={(checked) => {
this.setState({
check:!this.state.check
})
if(check_folder[sectionID] == false){
check_folder[sectionID] = true
this.setState({
check:check_folder// has to do this because we cant change the single element in the array
})
}else{
check_folder[sectionID] = false
this.setState({
check:check_folder// has to do this because we cant change the single element in the array
})
}
console.log(check_folder)a
}}
/>
</TouchableOpacity>
</View>
}
/>
</View>
)}
}
export default ApproveContent
const style = StyleSheet.create({
TextStyle:{
fontFamily: 'Roboto-Bold',
fontSize:15,
},
approveButton: {
bottom:0,
left:0,
alignItems: 'center',
}
})