React Native - How to get picker data - android

I am new to React Native. If I asked something so easy sorry 'bout that.
I have Picker Component in my App.js.
I want to go to component depending on a Picker item.
So, for example; I picked the second item of Picker, when I Clicked the 'Next' button it has to go to second.js
Here is some Part of my Code:
My App.js:
...
...
function Third({ navigation }) {
return (
<View style={styles.container}>
<Text style={styles.circle}>2</Text><Text style={styles.titles}>Operating Mode</Text>
<Text />
<Text style={styles.description}>Please select operating mode</Text><Text/>
<Picker/>
<Button title="Next" style={styles.buttons} color="#FF7F11" onPress={() => navigation.navigate("Fourth")}/><Text/>
<Button title="Back" style={styles.buttons} color="#FF7F11" onPress={() => navigation.goBack()} /><Text/>
</View>
);
}
...
...
and my Picker.js:
import React, { Component } from "react";
import { Text, View, StyleSheet } from "react-native";
import { Picker } from "#react-native-picker/picker";
class Picker extends Component {
state = {router: ''}
updaterouter = (router) => {
this.setState({ router: router })
}
render() {
return (
<View>
<Picker selectedValue={this.state.router} style={styles.drop} onValueChange = {this.updaterouter}>
<Picker.Item label="Rt" value="rt" />
<Picker.Item label="Ap" value="ap" />
<Picker.Item label="Rp" value="rp" />
<Picker.Item label="Wp" value="wp" />
</Picker><Text></Text>
</View>
);
}
}
export default Picker
const styles = StyleSheet.create({
drop: {
height: 30,
width: 200,
backgroundColor: "#FFF"
}
})

One option is to pass the value to the parent via a callback function, something like this:
updaterouter = (router) => {
this.setState({ router: router })
props.onRouterUpdated && props.onRouterUpdated(router)
}
<Picker onRouterUpdated={(r)=>{/*do something with r*/}}/>
Another would be to use common store (e.g. Redux)

Related

onPress() not working on expo v42.0.0. Using TouchableOpacity for the rounded button

I used useState hook. onSubmitEditing i.e. pressing enter the command setTmpItem should run and should set the value of inputBox in the variable tmpItem.
addSubject prop passed is also a hook, which can be seen in 2nd code(app.js)
But when I press the RoundedButton, it is not console logging neither 1 nor 2 and also addSubject(tmpItem) not working.
Focus.js below
import React, { useState } from 'react';
import { View, StyleSheet, Text } from 'react-native';
import { TextInput } from 'react-native-paper';
import { RoundedButton } from '../../components/RoundedButton';
export const Focus = ({ addSubject }) => {
const [tmpItem, setTmpItem] = useState(null);
return (
<View style={styles.container}>
<View>
<Text> What would you like to focus on? </Text>
<View>
<TextInput
onSubmitEditing={({ nativeEvent: { text } }) => {
setTmpItem(text);
}}
/>
<RoundedButton
size={50}
title="+"
onPress={() => {
console.log("1");
addSubject(tmpItem);
console.log("2");
}}
/>
</View>
</View>
</View>
);
};
App.js below
//App.js is the central point to glue everything
import React, { useState } from 'react';
import { View, StyleSheet, Text } from 'react-native';
import { Focus } from './src/features/focus/Focus';
export default function App() {
const [focusSubject, setFocusSubject] = useState(null);
return (
<View>
{focusSubject ? (
<Text>Where am I going to build a timer</Text>
) : (
<Focus addSubject = {setFocusSubject}/>
)}
<Text>{focusSubject}</Text>
</View>
);
}
RoundedButton.js below
import React from 'react';
import { TouchableOpacity, View, Text, StyleSheet } from 'react-native';
export const RoundedButton = ({
style = {},
textStyle = {},
size = 125,
...props
}) => {
return (
<TouchableOpacity>
<Text>{props.title}</Text>
</TouchableOpacity>
);
};
You need to handle your TextInput for Focus.js by passing the value and onChangeText props in TextInput component like:
export const Focus = ({ addSubject }) => {
const [tmpItem, setTmpItem] = useState(null);
const onSubmit = () => {
//and handle this onSubmit function the way you want to
//or pass the addSubject props
addSubject(tmpItem);
}
return (
<View style={styles.container}>
<View>
<Text> What would you like to focus on? </Text>
<View>
<TextInput
onChangeText={setTmpItem}
value={tmpItem}
onSubmitEditing={() => onSubmit()}
/>
<RoundedButton
size={50}
title="+"
onPress={() => {
addSubject(tmpItem);
}}
/>
</View>
</View>
</View>
);
};
Also, the reason why console.log not working in RoundedButton is, you're not passing that onPress prop to your TouchableOpacity of RoundedButton. In RoundedButton.js do it like this:
import React from 'react';
import { TouchableOpacity, View, Text, StyleSheet } from 'react-native';
export const RoundedButton = ({
style = {},
textStyle = {},
size = 125,
...props
}) => {
return (
<TouchableOpacity onPress={props.onPress}>
<Text>{props.title}</Text>
</TouchableOpacity>
);
};
props.onPress is what you're missing.
Hope this works for you.

React Native Alert.alert() only works on iOS and Android not web

I just started learning and practicing React Native and I have run into the first problem that I cant seem to solve by myself.
I have the following code, which is very simple, but the Alert.alert() does not work when I run it on the web. if I click the button nothing happens, however, when i click the button on an iOS or android simulator it works fine.
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, Button, View, Alert } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<Text style={styles.headerStyle} >Practice App</Text>
<Text style={{padding: 10}}>Open up App.js to start working on your app!</Text>
<Button
onPress={() => alert('Hello, Nice To Meet You :)')}
title="Greet Me"
/>
<StatusBar style="auto" />
</View>
);
}
I also know that alert() works on all three devices, however, I want to understand why Alert.alert() only works for iOS and Android.
My question is more so for understanding rather than finding a solution. Is the only solution to use alert(), or am I implementing Alert.alert() in the wrong way?
This workaround basically imitates react-native's Alert behavior with browsers' window.confirm method:
# alert.js
import { Alert, Platform } from 'react-native'
const alertPolyfill = (title, description, options, extra) => {
const result = window.confirm([title, description].filter(Boolean).join('\n'))
if (result) {
const confirmOption = options.find(({ style }) => style !== 'cancel')
confirmOption && confirmOption.onPress()
} else {
const cancelOption = options.find(({ style }) => style === 'cancel')
cancelOption && cancelOption.onPress()
}
}
const alert = Platform.OS === 'web' ? alertPolyfill : Alert.alert
export default alert
Usage:
Before:
import { Alert } from 'react-native'
Alert.alert(...)
After:
import alert from './alert'
alert(...)
Source & Credits: https://github.com/necolas/react-native-web/issues/1026#issuecomment-679102691
React Native is an open-source mobile application framework for Android, iOS and Web but there is not an Alert Component for Web but I have found a package which will provide you solutation. That is it to install package
npm i react-native-awesome-alerts
This example will help you
import React from "react";
import { StyleSheet, Text, View, TouchableOpacity } from "react-native";
import Alert from "react-native-awesome-alerts";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = { showAlert: false };
}
showAlert = () => {
this.setState({
showAlert: true,
});
};
hideAlert = () => {
this.setState({
showAlert: false,
});
};
render() {
const { showAlert } = this.state;
return (
<View style={styles.container}>
<Text>Practice App</Text>
<Text style={{ padding: 10 }}>
Open up App.js to start working on your app!
</Text>
<TouchableOpacity
onPress={() => {
this.showAlert();
}}
>
<View style={styles.button}>
<Text style={styles.text}>Greet Me</Text>
</View>
</TouchableOpacity>
<Alert
show={showAlert}
message="Hello, Nice To Meet You :"
closeOnTouchOutside={true}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center",
backgroundColor: "#fff",
},
button: {
margin: 10,
paddingHorizontal: 10,
paddingVertical: 7,
borderRadius: 5,
backgroundColor: "#AEDEF4",
},
text: {
color: "#fff",
fontSize: 15,
},
});

How to get variable react native

I'm using react native expo for the following project basically i want to retrive the selected item form an flat list and display it in a modal
import React,{ Component}from 'react';
import {View,Text,Image,StyleSheet,Modal,Button} from 'react-native';
import { FlatList, TouchableOpacity, ScrollView } from 'react-native-gesture-handler';
import Card from '../shared/card';
import { AppLoading } from 'expo';
import * as Font from 'expo-font';
export default class MealSearch extends Component{
constructor(props){
super(props)
this.state = {
loaded:false,
show:false,
key:''
}}
render(){
const meal= [ {title:'My hero Academia',img:{uri:'https://i.cdn.turner.com/adultswim/big/img/2018/05/10/MHA_Header.png'}, body:'Rating : 4.5/5' , id :'1'},
{title:'Naruto',img:{uri:'https://store-images.s-microsoft.com/image/apps.15041.71343510227343465.377174a9-abc8-4da3-aaa6-8874fdb9e2f5.00fc0a9e-295e-40ca-a391-58ed9f83e9a0?mode=scale&q=90&h=1080&w=1920&background=%23FFFFFF'}, body:'Rating : 5/5' , id :'2'},
{title:'Attack On Titan',img:{uri:'https://www.denofgeek.com/wp-content/uploads/2013/12/attack-on-titan-main.jpg?fit=640%2C380'}, body:'Rating : 4.5/5' , id :'3'},
{title:'Fate: Unlimited Blade Works',img:{uri:'https://derf9v1xhwwx1.cloudfront.net/image/upload/c_fill,q_60,h_750,w_1920/oth/FunimationStoreFront/2066564/Japanese/2066564_Japanese_ShowDetailHeaderDesktop_496a6d81-27db-e911-82a8-dd291e252010.jpg'}, body:'Rating : 4.5/5' , id :'4'}
]
const handlePress = (meal_data) =>{
this.setState({show: true});
this.setState({selectedMeal:meal_data});
console.log(meal_data)
}
return(
<View style={styles.view} >
<FlatList
keyExtractor={item => item.id}
data={meal}
renderItem={({item})=>(
<Card>
<TouchableOpacity onPress={(_item)=>{handlePress(item)}}>
<View style={styles.mealItem}>
<Image style={{width:300,height:150}} resizeMode={'contain'} source={item.img} marginLeft={30}/>
<View style={styles.descrip}>
<Text style={styles.rating}>{item.title}</Text>
<Text style={styles.name}>{item.body}</Text>
</View>
</View>
</TouchableOpacity>
</Card>
)}
/>
<Modal
transparent={true}
visible={this.state.show}
>
<View style={styles.modal}>
<View style={styles.inModal}>
<Button title='End' onPress={()=>{this.setState({show:false})}}/>
</View>
</View>
</Modal>
</View>
);}
}
this is the code I'm currently working on I want the 'meal_data' in 'handlePress' to be displayed inside my modal 'meal_data' is the selected item from the flat list .
<Modal
transparent={true}
visible={this.state.show}
>
<View style={styles.modal}>
<View style={styles.inModal}>
<Button title='End' onPress={()=>{this.setState({show:false})}}/>
</View>
</View>
</Modal>
I want to display it in here above the button
Change these lines of code:
Change: <TouchableOpacity onPress={(_item)=>{handlePress(item)}}>
To
<TouchableOpacity onPress={() => this.handlePress(item)}>
Delete this code inside render():
const handlePress = (meal_data) =>{
this.setState({show: true});
this.setState({selectedMeal:meal_data});
console.log(meal_data)
}
And put this code above render() medthod instead:
handlePress = (meal_data) =>{
this.setState({show: true, selectedMeal: meal_data});
console.log(meal_data)
}
Inside state
this.state = {
loaded:false,
show:false,
key:''
selectedMeal: null // Add this property
}}
After that, you'll be able to access selectedMeal inside your Modal.
Put this code inside the Modal (or somewhere else)
{this.state.selectedMeal && (
<View>
<Text>{this.state.selectedMeal.title}</Text>
</View>
)}
First of declare your handlePress outside of render method. Other thing is that this.setState() is Async so, first set you data then show the modal. Your final code should look like this :
import React, { Component } from 'react';
import { View, Text, Image, StyleSheet, Modal, Button } from 'react-native';
import { FlatList, TouchableOpacity, ScrollView } from 'react-native-gesture-handler';
import Card from '../shared/card';
import { AppLoading } from 'expo';
import * as Font from 'expo-font';
export default class MealSearch extends Component {
constructor(props) {
super(props)
this.state = {
loaded: false,
show: false,
key: ''
}
}
handlePress = (meal_data) => {
this.setState({ selectedMeal: meal_data }, () => {
this.setState({ show: true });
});
console.log(meal_data)
}
render() {
const meal = [
{ title: 'My hero Academia', img: { uri: 'https://i.cdn.turner.com/adultswim/big/img/2018/05/10/MHA_Header.png' }, body: 'Rating : 4.5/5', id: '1' },
{ title: 'Naruto', img: { uri: 'https://store-images.s-microsoft.com/image/apps.15041.71343510227343465.377174a9-abc8-4da3-aaa6-8874fdb9e2f5.00fc0a9e-295e-40ca-a391-58ed9f83e9a0?mode=scale&q=90&h=1080&w=1920&background=%23FFFFFF' }, body: 'Rating : 5/5', id: '2' },
{ title: 'Attack On Titan', img: { uri: 'https://www.denofgeek.com/wp-content/uploads/2013/12/attack-on-titan-main.jpg?fit=640%2C380' }, body: 'Rating : 4.5/5', id: '3' },
{ title: 'Fate: Unlimited Blade Works', img: { uri: 'https://derf9v1xhwwx1.cloudfront.net/image/upload/c_fill,q_60,h_750,w_1920/oth/FunimationStoreFront/2066564/Japanese/2066564_Japanese_ShowDetailHeaderDesktop_496a6d81-27db-e911-82a8-dd291e252010.jpg' }, body: 'Rating : 4.5/5', id: '4' }
]
return (
<View style={styles.view} >
<FlatList
keyExtractor={item => item.id}
data={meal}
renderItem={({ item }) => (
<Card>
<TouchableOpacity onPress={() => { this.handlePress(item) }}>
<View style={styles.mealItem}>
<Image style={{ width: 300, height: 150 }} resizeMode={'contain'} source={item.img} marginLeft={30} />
<View style={styles.descrip}>
<Text style={styles.rating}>{item.title}</Text>
<Text style={styles.name}>{item.body}</Text>
</View>
</View>
</TouchableOpacity>
</Card>
)}
/>
<Modal
transparent={true}
visible={this.state.show}
>
<View style={styles.modal}>
<View style={styles.inModal}>
<Button title='End' onPress={() => { this.setState({ show: false }) }} />
</View>
</View>
</Modal>
</View>
);
}
}

Native-Base - CheckBox inside List not getting checked

I have imported CheckBox from NativeBase. On clicking the Checkbox, it calls the toggleCheckBox function to either add or remove the item.ids from the array and also set the flag to true or false based on the contents of the array.
I can see that the toggleCheckBox function works properly and it sets the array with item ids properly and the flag is also fine on click of the CheckBox. But, the checkbox inside the ListItem is not checked when the checkbox is clicked though the toggle function is called properly.
I also noticed that the log "MS CB2: " right above the List is printed after clicking the CheckBox but the log inside the List 'MS insideList :' is not printed. I am assuming that List is not rendered after the toggleCheckBox function is called.
Here is the code:
class MSScreen extends Component {
constructor(props){
super(props);
//this.toggleCheckbox = this.toggleCheckbox.bind(this);
this.state = {
isLoading: true,
checkboxes : [],
plans: {},
};
}
componentDidMount(){
console.log("MS inside componentDidMount");
fetch('http://hostname:port/getData')
.then((response) => {console.log('response'); return response.json();})
.then((responseJson) => {console.log('responseData: '+responseJson); this.setState({isLoading : false, plans : responseJson}); return;})
.catch((err) => {console.log(err)});
}
toggleCheckbox(id) {
let checkboxes = this.state.checkboxes;
if(checkboxes && checkboxes.includes(id)){
const index = checkboxes.indexOf(id);
checkboxes.splice(index, 1);
} else {
checkboxes = checkboxes.concat(id);
}
this.setState({checkboxes});
console.log("MS check a4: "+checkboxes && checkboxes.includes(id))
}
render() {
if (this.state.isLoading) {
return <View><Text>Loading...</Text></View>;
}
const plans = this.state.plans;
const { params } = this.props.navigation.state.params;
const checkboxes = this.state.checkboxes;
console.log("MS CB1: "+checkboxes)
return (
<Container>
<Content>
<View>
{console.log("MS CB2: "+checkboxes)}
<List
dataArray={plans.data}
renderRow={(item, i) => {
console.log('MS insideList : '+checkboxes && checkboxes.includes(item.id))
return(
<ListItem
key={item.id}
>
<Left>
<CheckBox
onPress={() => this.toggleCheckbox(item.id)}
checked={checkboxes && checkboxes.includes(item.id)}
/>
</Left>
<Text>
{item.name}
</Text>
</ListItem>)}}
/>
</View>
</Content>
</Container>
);
}
}
How do I get the CheckBox to get checked inside the List?
For the benefit of the other users, here is the code fix based on the suggestion from Supriya in the comments below:
SOLUTION
<FlatList
extraData={this.state}
data={plans.data}
keyExtractor={(item, index) => item.id}
renderItem={({item}) => {
const itemName = item.name;
return(
<ListItem>
<CheckBox
onPress={() => this.toggleCheckbox(item.id)}
checked={checkboxes && checkboxes.includes(item.id)}
/>
<Body>
<Text style={styles.planText}>
{item.name}
</Text>
</Body>
</ListItem>)}}
/>
Version:
native-base#2.3.5
react-native#0.50.4
Device: Android
CRNA app with Expo
There is a similar issue on github, https://github.com/GeekyAnts/NativeBase/issues/989 with solution
It works with straightforward code without listItem.
The following example handles the checkboxes as radio buttons, but the onPress functions can be changed easily to allow multiple selection.
import React, { Component } from 'react';
import { View } from 'react-native';
import { CheckBox, Text } from 'native-base';
export default class SignupScreen extends Component {
state = {
one: false,
two: false,
three: false
};
render() {
return (
<View style={{ alignItems: 'flex-start' }}>
<View style={{ flexDirection: 'row' }}>
<CheckBox checked={this.state.one}
style={{ marginRight: 20 }}
onPress={this.onePressed.bind(this)}/>
<Text>One</Text>
</View>
<View style={{ flexDirection: 'row' }}>
<CheckBox checked={this.state.two}
style={{ marginRight: 20 }}
onPress={this.twoPressed.bind(this)}/>
<Text>Two</Text>
</View>
<View style={{ flexDirection: 'row' }}>
<CheckBox checked={this.state.three}
style={{ marginRight: 20 }}
onPress={this.threePressed.bind(this)}/>
<Text>Three</Text>
</View>
</View>
);
}
// checkbox functions
// if clicked button was set, only clear it
// otherwise, set it and clear the others
onePressed() {
if (this.state.one)
this.setState({ one: false });
else
this.setState({ one: true, two: false, three: false });
}
twoPressed() {
if (this.state.two)
this.setState({ two: false });
else
this.setState({ one: false, two: true, three: false });
}
threePressed() {
if (this.state.three)
this.setState({ three: false });
else
this.setState({ one: false, two: false, three: true });
}
}

Click event on words react native

I want to set different click listeners on different words of . Currently what i have is
<Text>Android iOS React Native<Text>
Now i want to know when user click on Android, iOS and React Native, i have to perform some analytics on that so need click listeners for seperate words.
Does any one have idea about it? I have checked this thread but i din't found it useful for my requirement.
Update
String i have given is just an example string, in real time i will be getting dynamic strings.
This is what i will be getting as dynamic string
{
"str":"Hi i am using React-Native, Earlier i was using Android and so on"
"tagWords":["React-Native","Android"]
}
And in output i want, "Hi i am using React-Native, Earlier i was using Android and so on"
with click event on "React-Native" and "Android". Is is possible?
The post you sent is the simplest way you can achieve the desired behavior. Sinse you need to have different listeners you need to implement different Text components.
Example
export default class App extends Component {
onTextPress(event, text) {
console.log(text);
}
render() {
return (
<View style={styles.container}>
<Text>
<Text onPress={(e) => this.onTextPress(e, 'Android')} style={styles.red}>{'Android '}</Text>
<Text onPress={(e) => this.onTextPress(e, 'iOS')} style={styles.purple}>{'iOS '}</Text>
<Text onPress={(e) => this.onTextPress(e, 'React Native')} style={styles.green}>{'React Native'}</Text>
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
red: {
fontSize: 20,
color: 'red'
},
purple: {
fontSize: 20,
color: 'purple'
},
green: {
fontSize: 20,
color: 'green'
}
});
Update 1 (Dynamic text)
render() {
const fixedString = 'I\'m a fixed string that slipleted';
const arrayOfStrings = ['These', 'are', 'strings', 'from', 'array'];
return (
<View style={styles.container}>
<Text style={styles.textContainer}>
{
fixedString.split(' ').map((str, index) => {
return (
<Text onPress={(e) => this.onTextPress(e, str)}>
{`${str}${index !== (fixedString.split(' ').lenght -1) && ' '}`}
</Text>
)
})
}
</Text>
<Text style={styles.textContainer}>
{
arrayOfStrings.map((str, index) => {
return (
<Text onPress={(e) => this.onTextPress(e, str)}>
{`${str}${index !== (arrayOfStrings.lenght -1) && ' '}`}
</Text>
)
})
}
</Text>
</View>
);
}
Update 2 (for example dynamic data)
removePunctuation = (text) => {
// this is a hack to remove comma from the text
// you may want to handle this different
return text.replace(/[.,\/#!$%\^&\*;:{}=\_`~()]/g,"");
}
render() {
const arrayOfObjects = [{
str: 'Hi i am using React-Native, Earlier i was using Android and so on',
tagWords: ['React-Native', 'Android']
}];
return (
<View style={styles.container}>
<Text style={styles.textContainer}>
{
arrayOfObjects.map((obj) => {
return obj.str.split(' ').map((s, index) => {
if ( obj.tagWords.indexOf(this.removePunctuation(s)) > -1 ) {
return (
<Text onPress={(e) => this.onTextPress(e, s)} style={styles.red}>
{`${s} ${index !== (obj.str.split(' ').lenght - 1) && ' '}`}
</Text>
)
} else return `${s} `;
})
})
}
</Text>
</View>
);
}
all you need to use is TouchableOpacity(for the tap effect and clicks), View for the alignment of texts. and certain styling. I am providing you the code snippet that will work for you , all other syntax will remain same
import {Text, View, TouchableOpacity} from 'react-native'
<View style={{flexDirection:'row'}}>
<TouchableOpacity onPress={{()=>doSomethingAndroid()}}>
<Text>Android</Text>
</TouchableOpacity>
<TouchableOpacity onPress={{()=>doSomethingiOS()}}><Text> iOS</Text>
</TouchableOpacity>
<TouchableOpacityonPress={{()=>doSomethingReactNative()}}><Text> React Native</Text>
</TouchableOpacity>
</View>
i hope this works, comment back if any issue happens
You can wrap each clickable words into 'TouchableOpacity' component, and tract the onPress event as follows
<View style={{flexDirection: 'row'}}>
<TouchableOpacity onPress={() => {
console.log('Android Clicked');
}}>
<Text>Android</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => {
console.log('iOS Clicked');
}}>
<Text>Ios</Text>
</TouchableOpacity>
</View>
Please do adjust the spacing between words.
Edit:
For dynamic string you can proceed as follows
...
handleWordClick(str, handler) {
var words = str.split(' '), // word separator goes here,
comp = [];
words.forEach((s, ind) =>{
comp.push(
<TouchableOpacity key={ind} onPress={() => handler.call(this, s)}>
<Text>{s}</Text>
</TouchableOpacity>
);
})
return comp;
}
render() {
var comp = this.handleWordClick('Android iOS React-Native', (word) => {
//handle analytics here...
console.log(word);
});
return (
<View>
...
<View style={{flexDirection: 'row'}}>
{comp}
</View>
...
</View>
)
}
I am not sure what will be your word separator as the example you have given has 'React Native' as single word. Please pay attention on this part.
Hope this will help you.

Categories

Resources