is multiple <Picker> within a <view> is possible? - javascript

If I need to use <Picker>..</Picker> more than once within a <View>..</View> how can I pick the selected VALUE of different <Picker> as this.state.PickerValue gives the selected value.

Try something like this
Constructor
constructor(props) {
super(props);
this.state = {
language: '',
level: '',
};
}
You render method
<View style={styles.container}>
<Picker
selectedValue={this.state.language}
style={{ height: 50, width: '100%' }}
onValueChange={(itemValue, itemIndex) =>
this.setState({ language: itemValue })}>
<Picker.Item label="Java" value="java" />
<Picker.Item label="JavaScript" value="js" />
</Picker>
<Picker
selectedValue={this.state.level}
style={{ height: 50, width: '100%' }}
onValueChange={(itemValue, itemIndex) =>
this.setState({ level: itemValue })}>
<Picker.Item label="Beginner" value="beginner" />
<Picker.Item label="Intermediate" value="intermediate" />
<Picker.Item label="Professional" value="professional" />
</Picker>
</View>
Check out the live demo here
Read more about Picker API here

Use different state values, one for each picker.
import React, { Component } from 'react';
import { View, Picker } from 'react-native';
class PickersComp extends Component {
state = {
val1 : '',
val2: '',
val3: '',
}
render(){
return (
<View>
<Picker
selectedValue={this.state.val1}
style={{ height: 50, width: 100 }}
onValueChange={(itemValue, itemIndex) => this.setState({ val1: itemValue })}>
<Picker.Item label="Java" value="java" />
<Picker.Item label="JavaScript" value="js" />
</Picker>
<Picker
selectedValue={this.state.val2}
style={{ height: 50, width: 100 }}
onValueChange={(itemValue, itemIndex) => this.setState({ val2: itemValue })}>
<Picker.Item label="foo" value="foo" />
<Picker.Item label="bar" value="bar" />
</Picker>
<Picker
selectedValue={this.state.val3}
style={{ height: 50, width: 100 }}
onValueChange={(itemValue, itemIndex) => this.setState({ val3: itemValue })}>
<Picker.Item label="test" value="test" />
<Picker.Item label="test2" value="js" />
</Picker>
</View>
);
}
};

Related

React Native: How can i make My DRAWER working

I implemented Drawer code and installed Drawer from its original docs and added Drawer into my Project, but I can't see drawer, tried playing with flex but in vain
Here are my code, any and every help is highly appreciated
Thank you
import { createDrawerNavigator } from '#react-navigation/drawer';
import { NavigationContainer } from '#react-navigation/native';
function HomeScreen({ navigation }) {
return (
<View>
<Button
onPress={() => navigation.navigate('Notifications')}
title="Go to notifications"
/>
</View>
);
}
function NotificationsScreen({ navigation }) {
return (
<View >
<Button onPress={() => navigation.goBack()} title="Go back home" />
</View>
);
}
const Drawer = createDrawerNavigator();
export default function App() {
const [selectedValue, setSelectedValue] = useState(' ');
const [text, setText] = useState('');
const [data, setData] = useState(['']);
const [totalAmount, setTotalAmount] = useState(0)
return (
<TouchableWithoutFeedback onPress={() => {
Keyboard.dismiss();
}}>
<View style={styles.container}>
<View >
<Header />
<View style={styles.row}>
<TextInput style={styles.input}
underlineColorAndroid="transparent"
placeholder=" Amount "
placeholderTextColor="#9a73ef"
autoCapitalize="none"
keyboardType='numeric'
onChangeText={text => setText(text)}
value={text}
/>
<Picker
selectedValue={selectedValue}
style={{ height: 50, width: 150 }}
onValueChange={(itemValue, itemIndex) => setSelectedValue(itemValue)}
>
<Picker.Item value= " " label='Select Option' />
<Picker.Item label="Food" value="Food" />
<Picker.Item label="Transport" value="Transport" />
<Picker.Item label="Rent" value="Rent" />
<Picker.Item label="Other" value="Other " />
</Picker>
</View>
And here i put my DRAWER
<Text>TOTAL : {totalAmount}</Text>
<NavigationContainer>
<Drawer.Navigator initialRouteName="Home">
<Drawer.Screen name="Home" component={HomeScreen} />
<Drawer.Screen name="Notifications" component={NotificationsScreen} />
</Drawer.Navigator>
</NavigationContainer>
<Button
title="Save"
color="#841584"
accessibilityLabel="Learn more about this purple button"
onPress={() => {
if (text == 0 ) {
alert('Please enter the Amount ')
}
if (text && selectedValue != " "){
setData([...data, { name: text, selectedValue: selectedValue }
])
setTotalAmount(totalAmount + parseInt(text))
}}
}
/>
<View styles={styles.list}>
<FlatList
data={data}
renderItem={({ item }) => <React.Fragment>
<Text style={styles.item}> {item.name}$ Spend on "
{item.selectedValue}"</Text>
</React.Fragment>}
keyExtractor={(item, index) => index.toString()}
/>
</View>
</View>
</View>
</TouchableWithoutFeedback>
)};
Here is the styles for my project
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
input: {
margin: 15,
height: 40,
borderColor: 'black',
borderWidth: 2,
width: 80,
flex: 1,
},
input2: {
margin: 15,
height: 40,
borderColor: 'black',
borderWidth: 2,
width: 80,
flex: 1,
},
row: {
flexDirection: 'row'
},
item: {
textAlign: 'center',
marginTop: 20,
padding: 20,
fontSize: 20,
backgroundColor: 'steelblue'
},
list: {
marginTop: 20,
flex: 1
},
button: {
}
});
also in , i have header file
export default function Header() {
return (
<View style={styles.header}>
<Text style={styles.title}>Мои расходы </Text>
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
</View>
);
}
const styles = StyleSheet.create({
header: {
height: 80,
paddingTop: 38,
backgroundColor: 'red'
},
title: {
textAlign: 'center',
color: '#fff',
fontSize: 20,
fontWeight: 'bold'
}
})
Swipe Left to Right, Just check Your Drawer Came out or not. If Not then Your Drawer is not set up as mentioned in the document. Make a button on your header and onPress Method just call {() => this.props.navigation.openDrawer()}

REACT NATIVE: How can i make calculation with the Value of TextInput

I want to make a Total by adding the Values from TextInput in RN:
Here is my TextInput
<TextInput style={styles.input}
placeholder=" Amount "
placeholderTextColor="#9a73ef"
keyboardType='numeric'
onChangeText={text => setText(text)}
value={text}
/>
<Picker
selectedValue={selectedValue}
style={{ height: 50, width: 150 }}
onValueChange={(itemValue, itemIndex) => setSelectedValue(itemValue)}
>
<Picker.Item value='' label='Select Option' />
<Picker.Item label="Food" value="Food" />
<Picker.Item label="Transport" value="Transport" />
<Picker.Item label="Rent" value="Rent" />
<Picker.Item label="Other" value="Other " />
</Picker>
</View>
And TOTALis where i want to put my total Value by adding Value of TextInputs
<Text>TOTAL : </Text>
<Button
title="Save"
color="#841584"
accessibilityLabel="Learn more about this purple button"
onPress={() => {
if (text && selectedValue) setData([...data, { name: text, selectedValue: selectedValue }
])
}} />
<View styles={styles.list}>
<FlatList
data={data}
renderItem={({ item }) => <React.Fragment>
<Text style={styles.item}> {item.name} Dollars to "{item.selectedValue}"</Text>
</React.Fragment>}
keyExtractor={(item, index) => index.toString()}
/>
</View>
</View>
</View>
</TouchableWithoutFeedback>
)};
I tried adding them they are Strings , i used to parseInt() but didnt work?
Here is the ScreenShot of my App
declear variable for total Amount like this
const [totalAmount,setTotalAmount] = useState(0)
update totalAmount value on save button
<Button
title="Save"
color="#841584"
accessibilityLabel="Learn more about this purple button"
onPress={() => {
if (text && selectedValue) {
setData([...data, { name: text,
selectedValue: selectedValue }
])
setTotalAmount(totalAmount + parseInt(text))
}
}} />
and use this variable in your html
<Text>TOTAL : {totalAmount}</Text>
no I was talking about this. check here
<View styles={styles.list}>
(data.length > 0)?
<FlatList
data={data}
renderItem={({ item }) => <React.Fragment>
<Text style={styles.item}> {item.name} Dollars to "
{item.selectedValue}"</Text>
</React.Fragment>}
keyExtractor={(item, index) => index.toString()}
/>
: null
</View>

React Navigation Header Button (V5 / Version 5.x): Show Menu Item

I am using React-Native-Paper's Menu Component
I am trying to show Menu item from the header after tapping an icon.
So far I have managed to show list of item on the screen only.
However, I want to show the menu list from the header.
Due to React Navigation's update from version:4.x to version:5.x, I am a bit confused on how to work this out. I tried following the example here but still I need some time to fully understand hook and the way it works.
All kinds of help would be appreciated.
Workable/Testable code link, code snippets and screenshots provided below:
Snack Link
Register.js:
import { TextInput, Button, Menu, Divider, Provider } from 'react-native-paper';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
class Register extends Component {
constructor(props) {
super(props);
this.state = {
visible: false,
}
}
//[ TEST DROP DOWN MENU ]
_openMenu = () => this.setState({ visible: true });
_closeMenu = () => this.setState({ visible: false });
renderMenuExample() {
return (
<View
style={{
paddingTop: 50,
flexDirection: 'row',
justifyContent: 'center'
}}>
<Menu
visible={this.state.visible}
onDismiss={this._closeMenu}
anchor={
< TouchableOpacity
onPress={this._openMenu}
style={{ marginHorizontal: 20 }}
>
<MaterialCommunityIcons name="earth" size={30} style={{ color: 'black' }} />
</TouchableOpacity>
}
>
<Menu.Item onPress={() => { }} title="Item 1" />
<Menu.Item onPress={() => { }} title="Item 2" />
<Divider />
<Menu.Item onPress={() => { }} title="Item 3" />
</Menu>
</View>
);
}
//[ TEST DROP DOWN MENU ]
render() {
return (
<Provider>
{this.renderMenuExample()}
</Provider>
);
}
}
export default Register;
App.js:
import { TextInput, Button, Menu, Divider, Provider } from 'react-native-paper';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import AntDesign from 'react-native-vector-icons/AntDesign';
const Stack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Register"
component={Register}
options={{
headerBackImage: () => (
<AntDesign name="close" size={30} style={{ color: 'white' }} />
),
headerTitle: () => (
<View>
<Text style={{ flex: 1, fontSize: 20, fontWeight: 'bold', alignSelf: 'center', color: 'white' }}>
Register
</Text>
</View>
),
headerRight: () => (
<TouchableOpacity
onPress={() => {/* I WANT TO SHOW THE MENU HERE */ }}
style={{ marginHorizontal: 20 }}
>
<MaterialCommunityIcons name="earth" size={30} style={{ color: 'white' }} />
</TouchableOpacity>
),
headerStyle: {
backgroundColor: '#2e46ff',
},
}}
/>
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
Screenshot:
One possible solution would be to wrap the navigation container with a provider and have a separate component for the menu.
Tried this with your snack and it works
The code would be as below.
const CustomMenu = () => {
const [showMenu, setShowMenu] = React.useState(false);
return (
<View style={{}}>
<Menu
visible={showMenu}
onDismiss={() => setShowMenu(false)}
anchor={
<TouchableOpacity onPress={() => setShowMenu(true)}>
<MaterialCommunityIcons
name="earth"
size={30}
style={{ color: 'black' }}
/>
</TouchableOpacity>
}>
<Menu.Item onPress={() => {}} title="Item 1" />
<Menu.Item onPress={() => {}} title="Item 2" />
<Divider />
<Menu.Item onPress={() => {}} title="Item 3" />
</Menu>
</View>
);
};
function App() {
return (
<Provider>
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Register"
component={Register}
options={{
headerBackImage: () => (
<AntDesign name="close" size={30} style={{ color: 'white' }} />
),
headerTitle: () => (
<View>
<Text
style={{
flex: 1,
fontSize: 20,
fontWeight: 'bold',
alignSelf: 'center',
color: 'white',
}}>
Register
</Text>
</View>
),
headerRight: () => <CustomMenu />,
headerStyle: {
backgroundColor: '#2e46ff',
},
}}
/>
</Stack.Navigator>
</NavigationContainer>
</Provider>
);
}

Using Constructor(props) without Class Component

I have created a search bar in TypeScript but for now I am unable to type anything into it. All the control component tutorials that I have seen suggest to use constructor(props) or so. If I use it in my code, I get errors.
Is there any way to use it without having a class component?
For instance, I am using a const() for my page. Is there any way I can make the search bar of this functional?
const userSearchPage = () => (
<div>
<PermanentDrawerLeft></PermanentDrawerLeft>
<div className='main-content'>
<MuiThemeProvider>
<DropDownMenu >
<MenuItem style={{ fontSize: "20px" }} primaryText="Search By" />
<MenuItem value={1} style={{ fontSize: "20px" }} primaryText="First Name" />
<MenuItem value={1} style={{ fontSize: "20px" }} primaryText="Last Name" />
</DropDownMenu>
</MuiThemeProvider>
<SearchBar
onChange={() => console.log('onChange')}
onRequestSearch={() => console.log('onRequestSearch')}
style={{
margin: '0 auto',
maxWidth: 800
}}
/>
</div>
</div>
);
You must use the useState hook in a functional component.
const userSearchPage = () => {
const [value, setValue] = React.useState('');
return (
<div>
<PermanentDrawerLeft></PermanentDrawerLeft>
<div className='main-content'>
<MuiThemeProvider>
<DropDownMenu >
<MenuItem style={{ fontSize: "20px" }} primaryText="Search By" />
<MenuItem value={1} style={{ fontSize: "20px" }} primaryText="First Name" />
<MenuItem value={1} style={{ fontSize: "20px" }} primaryText="Last Name" />
</DropDownMenu>
</MuiThemeProvider>
<SearchBar
onChange={(value) => setValue(value) }
value={value}
onRequestSearch={() => console.log('onRequestSearch')}
style={{
margin: '0 auto',
maxWidth: 800
}}
/>
</div>
</div>
)} ;
Props in functional component's are simply parameters!
function SearchBar (props) {
let searchbartext = document.getElementById('searchbartext')
searchbartext.addEventListener('change', (e) => {
props.onChange(e)
}
return (
<form onsubmit={(e) => props.onRequestChange(e)}>
<input id="searchbartext" style={props.style} />
</form>
)
}
const UserSearchPage = () => {
function onRequestSearch (e) {
console.log.('request search', e)
}
function onChange(e) {
console.log('onChange')
}
return (
{SearchBar({
onChange:onChange,
onRequestSearch:onRequestSearch,
style:{
margin: '0 auto',
maxWidth: 800
}
})}
)
}
Edit: you also have to call functional component's as functions, not with <> syntax like class components. I used the term "props" inside SearchBar(props) but it's just following Reacts naming convention. You could just as easily replace it with SearchBar(bananas).

React Native Picker: Set and Get different Picker Values

I am working with React Native Picker and I have created two states: userType and name.
However, there are two userType: Freelancer, Client. There are also two name for each userType, and these are: Freelancer 1, Freelancer 2, and Client 1, Client 2.
Currently, I have two pickers. One has the userType and the other has name. Regardless of the userType selected, the 2nd picker shows all the name i.e Freelancer 1, Freelancer 2, Client 1, Client 2.
But this is what I am trying to achieve:
HOW TO: Instead of showing all the name, I want to show specific name depending on the userType selected. For example: if userType === Freelancer, then name picker should display only Freelancer 1, Freelancer 2. And, if userType === Client, then name picker should display only Client 1, Client 2.
Code snippet Provided Below:
constructor(props) {
super(props);
this.state = {
userType: '',
name: '',
}
}
render() {
return (
<View>
<View style={{ flexDirection: 'row' }}>
<Text style={styles.titleStyle}>User Type</Text>
<View style={styles.pickerStyle}>
{<Picker
mode='dropdown'
selectedValue={this.state.userType}
onValueChange={(itemValue, itemIndex) =>
this.setState({ userType: itemValue })
}>
<Picker.Item label="Select User Type" value="" />
<Picker.Item label="Freelancer" value="Freelancer" />
<Picker.Item label="Client" value="Client" />
</Picker>}
</View>
</View>
<View style={{ flexDirection: 'row' }}>
<Text style={styles.titleStyle}>Name</Text>
<View style={styles.pickerStyle}>
{<Picker
mode='dropdown'
selectedValue={this.state.name}
onValueChange={(itemValue, itemIndex) =>
this.setState({ name: itemValue })
}>
<Picker.Item label="Please Select" value="" />
<Picker.Item label="Freelancer 1" value="Freelancer 1" />
<Picker.Item label="Freelancer 2" value="Freelancer 2" />
<Picker.Item label="Client 1" value="Client 1" />
<Picker.Item label="Client 2" value="Client 2" />
</Picker>}
</View>
</View>
</View>
);
};
App Screenshot:
you should have function that return usernames based on user type
renderUserNames() {
if(this.state.userType=='Freelancer'){
return [<Picker.Item label="Freelancer 1" value="Freelancer 1" />,
<Picker.Item label="Freelancer 2" value="Freelancer 2" />]
}else{
return [<Picker.Item label="Client 1" value="Client 1" />,
<Picker.Item label="Client 2" value="Client 2" />]
}
}
then inside render function you can call i like
render() {
let options=this.renderUserNames();
return (
<View>
<View style={{ flexDirection: 'row' }}>
<Text style={styles.titleStyle}>User Type</Text>
<View style={styles.pickerStyle}>
{<Picker
mode='dropdown'
selectedValue={this.state.userType}
onValueChange={(itemValue, itemIndex) =>
this.setState({ userType: itemValue })
}>
<Picker.Item label="Select User Type" value="" />
<Picker.Item label="Freelancer" value="Freelancer" />
<Picker.Item label="Client" value="Client" />
</Picker>}
</View>
</View>
<View style={{ flexDirection: 'row' }}>
<Text style={styles.titleStyle}>Name</Text>
<View style={styles.pickerStyle}>
{<Picker
mode='dropdown'
selectedValue={this.state.name}
onValueChange={(itemValue, itemIndex) =>
this.setState({ name: itemValue })
}>
<Picker.Item label="Please Select" value="" />
{options}
</Picker>}
</View>
</View>
</View>
);
};

Categories

Resources