React Native Functional Component react-native-select2 onSelected Value not update - react-native

React Native Functional Component react-native-select2 onSelected Value not updateing.
https://www.npmjs.com/package/#schmelman/rns2
https://snack.expo.dev/#prem18mca/select2-functional
https://snack.expo.dev/#prem18mca/select2
import React, { useState } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
import Select2 from "react-native-select-two"
// You can import from local files
import AssetExample from './components/AssetExample';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
export default function App() {
const [data, setData] = useState(mockData);
const mockData = [
{ id: 1, name: "React Native Developer", checked: true}, // set default checked for render option item
{ id: 2, name: "Android Developer", color: '#f00' },
{ id: 3, name: "iOS Developer", color: '#f00' }
]
return (
<View style={styles.container}>
<Text style={styles.paragraph}>
Change code in the editor and watch it change on your phone! Save to get a shareable url.
</Text>
<Select2
style={{ borderRadius: 5 }}
colorTheme="blue"
popupTitle="Select item"
title="Select item"
data={mockData}
onSelect={data => {
setData({ data })
}}
cancelButtonText = "Cancel"
selectButtonText = "Select"
onRemoveItem={data => {
setData({ data })
}}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});

Try to update with npm i #marcelodiegues/react-native-select2. If it doesn't work, show your error message

Related

Why is React Native FlatList not working on Android but it is for Web?

I am using Expo to build a react native app with AWS for the backend.
I am trying to display a list of friends using FlatList and the AWS data. The list works and is visible on my web browser, but for some reason, it is not displaying on my Android phone. What might the issue be?
FriendsList.tsx
import { API, graphqlOperation } from 'aws-amplify';
import * as React from 'react';
import {useEffect, useState} from 'react';
import { FlatList, View, ScrollView, Text, StyleSheet } from 'react-native';
import { listUsers } from '../graphql/queries';
import FriendsListItem from '../components/FriendsListItem';
export default function FriendsList() {
const [ users, setUsers ] = useState([]);
useEffect( () => {
const fetchUsers = async () => {
try {
const usersData = await API.graphql(
graphqlOperation(
listUsers
)
)
setUsers(usersData.data.listUsers.items);
} catch (e) {
}
}
fetchUsers();
},[])
return (
<View style={ styles.container }>
<FlatList
style={{ width: '100%' }}
data={users}
renderItem={({ item }) => <FriendsListItem user={item} />}
keyExtractor={(item) => item.id}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
});
FriendsListItem.tsx
import * as React from 'react';
import { View, Text, StyleSheet, Image, TouchableWithoutFeedback } from 'react-native';
import { API, graphqlOperation, Auth } from "aws-amplify";
import { User } from './types';
export type FriendsListItemProps = {
user: User;
}
const FriendsListItem = ( props: FriendsListItemProps ) => {
const { user } = props;
return (
<TouchableWithoutFeedback>
<View style={styles.container}>
<View style={styles.lefContainer}>
<Image source={{ uri: user.imageUri }} style={styles.avatar}/>
<View style={styles.midContainer}>
<Text style={styles.username}>{user.name}</Text>
<Text numberOfLines={2} style={styles.status}>{user.email}</Text>
</View>
</View>
</View>
</TouchableWithoutFeedback>
);
}
export default FriendsListItem;
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
width: "100%",
justifyContent: 'space-between',
//height: '100%',
},
lefContainer: {
flexDirection: 'row',
padding: 16,
},
midContainer: {
justifyContent: 'space-around'
},
avatar: {
width: 60,
height: 60,
borderRadius: 50,
marginRight: 15,
},
username: {
fontWeight: 'bold',
fontSize: 16,
},
status: {
fontSize: 16,
color: 'grey',
},
});
Looking at the code example, in your FriendsListItem component, any time you use your "user" prop, you need to change it. For example, change this:
user.imageUri
to this:
user.item.imageUri
What you are passing in is an object (e.g. user), which then contains another object (e.g. item), which finally contains your data (e.g. imageUri).
I figured it out. Turns out I am just an idiot. The expo app on my phone was logged into a different account so that's why it wasn't showing any friends for that user.

Expo React Native - How to use ErrorRecovery?

The current Expo ErrorRecovery docs do not provide any example using ErrorRecovery.setRecoveryProps().
If you know how to use it the Managed workflow, so that it catches JS errors, let me know.
Thank you
I gave it a try:
import * as React from "react";
import { Text, View, StyleSheet } from "react-native";
import Constants from "expo-constants";
import { Button } from "react-native-paper";
import * as ErrorRecovery from "expo-error-recovery";
export default function App({ exp }) {
return (
<View style={styles.container}>
<Text style={styles.paragraph}>{JSON.stringify(exp.errorRecovery)}</Text>
<Button
onPress={() => {
ErrorRecovery.setRecoveryProps({ info: "User pressed crash button" });
throw "Crash!";
}}
>
Crash!
</Button>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
paddingTop: Constants.statusBarHeight,
backgroundColor: "#ecf0f1",
padding: 8
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: "bold",
textAlign: "center"
}
});
When you load the app initially, exp.errorRecovery will be null. If you click the "Crash!" button and reload then exp.errorRecovery will contain whatever you set with setRecoveryProps().
I think the idea is that you can use setRecoveryProps() to let your app know that it crashed and maybe provide some context about what happened just before the crash. I’ve never used it, though, so I’m not sure what a good use case is.
EDIT:
The above might not be all that useful, but you can combine it with the approach shown here (using a global error handler) to pass some information about the crash to the reloaded app:
import * as React from "react";
import { Text, View, StyleSheet } from "react-native";
import Constants from "expo-constants";
import { Button } from "react-native-paper";
import * as ErrorRecovery from "expo-error-recovery";
const defaultErrorHandler = ErrorUtils.getGlobalHandler();
const globalErrorHandler = (err, isFatal) => {
console.log("globalErrorHandler called!");
ErrorRecovery.setRecoveryProps({ info: err });
defaultErrorHandler(err, isFatal);
};
ErrorUtils.setGlobalHandler(globalErrorHandler);
export default function App({ exp }) {
return (
<View style={styles.container}>
<Text style={styles.paragraph}>{JSON.stringify(exp.errorRecovery)}</Text>
<Button
onPress={() => {
throw "Crash!";
}}
>
Crash!
</Button>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
paddingTop: Constants.statusBarHeight,
backgroundColor: "#ecf0f1",
padding: 8
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: "bold",
textAlign: "center"
}
});
for what it's worth, this is from the expo ErrorRecovery source code, so its essentially doing the same thing as the link you posted in your edit
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
import { Platform } from 'react-native';
import { getRecoveryPropsToSave } from './ErroRecoveryStore';
import ExpoErrorRecovery from './ExpoErrorRecovery';
if (Platform.OS !== 'web') {
const globalHandler = ErrorUtils.getGlobalHandler();
// ErrorUtils came from react-native
// https://github.com/facebook/react-native/blob/1151c096dab17e5d9a6ac05b61aacecd4305f3db/Libraries/vendor/core/ErrorUtils.js#L25
ErrorUtils.setGlobalHandler(async (error, isFatal) => {
if (ExpoErrorRecovery.saveRecoveryProps) {
await ExpoErrorRecovery.saveRecoveryProps(getRecoveryPropsToSave());
}
globalHandler(error, isFatal);
});
} else if (Platform.OS === 'web' && canUseDOM) {
window.addEventListener('error', () => {
ExpoErrorRecovery.saveRecoveryProps(getRecoveryPropsToSave());
});
}

Redux-form, onChange(value) returns undefined, custom Radio component

I am using Redux-form with a custom Radio Group and Button components. When i select a radio button, redux-logger seems to show that the state is updated with the correct values. However checked always returns false, and so the radio button style never gets updated.
console.log(value) returns the correct value
console.log(onChange(value) always returns undefined
console.log(checked) always returns false
RadioGroup.js
import React from 'react';
import PropTypes from 'prop-types';
import { View, Text, StyleSheet } from 'react-native';
import RadioButton from '../components/RadioButton';
import { COLOR_PRIMARY } from '../constants';
const styles = StyleSheet.create({
errorStyle: {
color: COLOR_PRIMARY,
},
});
const RadioGroup = (props) => {
const { radios, input: { value, onChange }, meta: { touched, error } } = props;
return (
<View>
{radios.map(radio => (
<RadioButton
key={radio.label}
{...radio}
onChange={onChange}
checked={radio.value === value}
/>
))}
{touched &&
(error && (
<View>
<Text style={styles.errorStyle}>{error}</Text>
</View>
))}
</View>
);
};
RadioGroup.propTypes = {
radios: PropTypes.arrayOf(
PropTypes.shape({
label: PropTypes.string.isRequired,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]).isRequired,
}),
).isRequired,
meta: PropTypes.shape({
touched: PropTypes.bool.isRequired,
error: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
}).isRequired,
input: PropTypes.shape({
value: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]).isRequired,
onChange: PropTypes.func.isRequired,
}).isRequired,
};
export default RadioGroup;
RadioButton.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { TouchableOpacity, View, Text, StyleSheet } from 'react-native';
import { COLOR_PRIMARY, TEXT_PRIMARY } from '../constants';
const styles = StyleSheet.create({
container: {
marginBottom: 20,
flexDirection: 'row',
alignItems: 'center',
},
circle: {
height: 24,
width: 24,
borderRadius: 12,
borderWidth: 2,
borderColor: COLOR_PRIMARY,
alignItems: 'center',
justifyContent: 'center',
},
circleFilled: {
height: 14,
width: 14,
borderRadius: 7,
backgroundColor: COLOR_PRIMARY,
},
labelStyle: {
color: TEXT_PRIMARY,
marginLeft: 10,
marginRight: 10,
},
});
export default class RadioButton extends Component {
handlePress = () => {
const { value, onChange, checked } = this.props;
onChange(value);
console.log(onChange(value));
console.log(value);
console.log(checked);
};
render() {
const { checked, label } = this.props;
return (
<View style={styles.container}>
<TouchableOpacity onPress={this.handlePress} style={styles.radioStyle}>
<View style={styles.circle}>
<View style={checked ? styles.circleFilled : null} />
</View>
</TouchableOpacity>
<Text style={styles.labelStyle}>{label}</Text>
</View>
);
}
}
RadioButton.propTypes = {
checked: PropTypes.bool.isRequired,
label: PropTypes.string.isRequired,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]).isRequired,
onChange: PropTypes.func.isRequired,
};
Form.js
<Field
name="sex"
radios={[{ label: 'Male', value: 'Male' }, { label: 'Female', value: 'Female' }]}
component={RadioGroup}
/>
So is there some problem with how i am using onChange?

react navigation giving error undefined is not an object(evaluating 'this.props.navigation')

I am new to react native I am using expo app to run my code I dont have index file as explained in other questions all the files i have are app.js ,login.js, router.js,home.js and My application flow should go like this Login> on button click > Home
but on button click I am getting error Undefined is not an object(evaluating 'this.props.navigation'),
please help me where i am going wrong.
thanks in advance.
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Login from './containers/Login/Login';
import {Navigate} from './containers/Navigation/Router';
import { AppRegistry } from 'react-native';
export default class App extends React.Component {
render() {
return (<Login navigation={this.props.navigation}/>);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
import React from 'react';
import { StyleSheet, Text,TextInput,Button,Image, View } from 'react-native';
import Navigate from '../Navigation/Router';
import RNChart from 'react-native-chart';
export default class Login extends React.Component{
static navigationOptions = {
title:'Login',
};
render() {
const navigate = this.props.navigation;
return (
<View style={styles.container}>
<RNChart style={styles.chart}
chartData={chartData}
verticalGridStep={5}
type="bar"
xLabels={xLabels}>
</RNChart>
<Image
source={require('../../NCS.png')}
/>
<TextInput
style={styles.textInput}
placeholder="Username"
/>
<TextInput
style={styles.textInput}
placeholder="Password"
secureTextEntry= {true}
/>
<Button
onPress={this._handlePress}
title="Login"
color="#0086b3"
/>
</View>
);
}
_handlePress(event) {
//navigate('Home')
this.props.navigation.navigate('Home', {name: 'Home'})
}
}
var chartData = [
{
name:'BarChart',
type:'bar',
color:'purple',
widthPercent:0.6,
data:[
30, 1, 1, 2, 3, 5, 21, 13, 21, 34, 55, 30
]
},
{
name:'LineChart',
color:'gray',
lineWidth:2,
showDataPoint:false,
data:[
10, 12, 14, 25, 31, 52, 41, 31, 52, 66, 22, 11
]
}
];
var xLabels = ['0','1','2','3','4','5','6','7','8','9','10','11'];
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
textInput: {
padding: 10,
width: 200,
},
chart: {
position: 'absolute', top: 16, left: 4, bottom: 4,right: 16
}
});
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import {Navigate} from '../Navigation/Router';
export default class Home extends React.Component {
static navigationOptions = {
title:'Home',
};
render() {
return (
<View style={styles.container}>
<Text> Work under progress</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import {StackNavigator} from 'react-navigation';
import Login from '../Login/Login';
import Home from '../Home/Home';
export default Navigate = StackNavigator({
Home: { screen: Home, },
});
The problem is that React Navigation is not connected to your App component as #Eden mentioned. The component you return in App needs to be your StackNavigator.
Here's a very good tutorial that show's this with a TabNavigator.
https://hackernoon.com/getting-started-with-react-navigation-the-navigation-solution-for-react-native-ea3f4bd786a4

React Native render and switch with navigator onPress

I've just started to develop with React Native a week ago.
Can anyone help me with simple render and switch onPress to another view?
I've read tones of examples, but most of them are cutted or not well documents as if on FaceBook Doc pages. There was no totally completed example with Nav.
Here is what was done yet - View that should be rendered 1st:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image,
TextInput,
TouchableHighlight,
TouchableNativeFeedback,
Platform,
Navigator
} from 'react-native';
export default class SignUp extends Component {
buttonClicked() {
console.log('Hi');
this.props.navigator.push({title: 'SignUp', component:SignUp});
}
render() {
var TouchableElement = TouchableHighlight;
if (Platform.OS === ANDROID_PLATFORM) {
TouchableElement = TouchableNativeFeedback;
}
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to Cross-Profi!
</Text>
<Text style={styles.field_row}>
<TextInput style={styles.stdfield} placeholder="Profession" />
</Text>
<Text style={styles.field_row}>
<TextInput style={styles.stdfield} placeholder="E-mail" />
</Text>
<Text style={styles.field_row}>
<TextInput style={styles.stdfield} secureTextEntry={true} placeholder="Password" />
</Text>
<TouchableElement style={styles.button} onPress={this.buttonClicked.bind(this)}>
<View>
<Text style={styles.buttonText}>Register</Text>
</View>
</TouchableElement>
{/* <Image source={require("./img/super_car.png")} style={{width:120,height:100}} />*/}
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'lightblue',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
color: 'darkred',
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
field_row: {
textAlign: 'center',
color: '#999999',
margin: 3,
},
stdfield: {
backgroundColor: 'darkgray',
height: 50,
width: 220,
textAlign: 'center'
},
button: {
borderColor:'blue',
borderWidth: 2,
margin: 5
},
buttonText: {
fontSize: 18,
fontWeight: 'bold'
}
});
const ANDROID_PLATFORM = 'android';
Navigator class that should render different views:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Platform,
Navigator
} from 'react-native';
var MainActivity = require('./app/MainActivity.js');
var SignUp = require('./app/SignUp.js');
class AwesomeProject extends Component {
/*constructor(props) {
super(props);
this.state = {text: ''};
}*/
render() {
// this.props.navigator.push({title:'SignUp'});
return (
<Navigator initialRoute={{title:'SignUp', component:SignUp}}
configureScene={() => {
return Navigator.SceneConfigs.FloatFromRight;
}}
renderScene={(route, navigator) =>
{
console.log(route, navigator);
if (route.component) {
return React.createElement(route.component, {navigator});
}
}
} />
);
}
}
const ANDROID_PLATFORM = 'android';
const routes = [
{title: 'MainActivity', component: MainActivity},
{title: 'SignUp', component: SignUp},
];
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
It doesn't seem to be clear whether there must be require of a class and declaration of class as export default.
There is an error: Element type is invalid: expected a string, ... but got object etc
Help with examples would be great. Thx
In your require call, you should either replace it import statement or use default property of require module i.e:
var MainActivity = require('./app/MainActivity.js').default;
or use
import MainActivity from "./app/MainActivity";
In ES6, require doesn't assign default property of module to variable.
See this blog post for better understanding of require working in es6