Adding Placeholder Kind of Functionality into React-Native Picker - reactjs

I have set up a reusable drop-menu component in my React-native app that uses the native picker. The less than ideal situation I'm running into is that since there is no placeholder property available on picker, if I add 'Select Type' to the list of menu items, that will show up as an option in the menu that opens up. That's obviously not ideal. How can I work a placeholder kind of functionality into this, so that 'Select Type' is initially displayed without showing up in the menu that pops up when the user presses to open the menu?
{
!this.state.otherTypeSelected ?
(
<View style={styles.forms.fieldContainer}>
<Text style={styles.forms.fieldLabel}>Type</Text>
<DropDownMenu
style={styles.forms.pickerContainer}
itemStyle={styles.forms.pickerItem}
items={[
{ label: 'A', value: 'A' },
{ label: 'B', value: 'B' },
{ label: 'C', value: 'C' },
{ label: 'D', value: 'D' },
{ label: 'Other', value: 'Other' }
]}
onSelectMenuValue={this.handleContactTypeSelection}
/>
</View>
) : null
}
And the DropDownMenu code looks like this:
export const DropDownMenu = (props) => {
const [selectedValue, setSelectedValue] = useState(null);
return (
<View style={componentStyles.container}>
<Picker
{...props}
selectedValue={selectedValue}
onValueChange={(itemValue, itemIndex) => {
props.onSelectMenuValue(itemValue),
setSelectedValue(itemValue)
}}
>
{props.items.map(item => <Picker.Item label={item.label} value={item.value} />)}
</Picker>
</View>
);
}
Note, while I could make my first menu item an empty string, with something like { label: '', value: 0 }, the space representing that value will still show up in my drop-menu, which is also not what I'm looking for.

The Picker in react-native has been deprecated. There are only two methods in order to use the Picker
Use any library for Picker.
Create your own Picker (where you will have all the controls with you.)
You can create a simple functional component such as:
Note: This was created in 5 mins, so don't expect this to be pretty :P But it is working
import React, { useState } from "react";
import { Text, View, StyleSheet, TouchableOpacity } from "react-native";
// Dropdown Item component
const DropDownItem = (props) => {
return <TouchableOpacity onPress={() => {
props.onPress(props.label)
props.hideDropdown(false)
}}>
<Text>{props.label}</Text>
</TouchableOpacity>
}
// Custom Picker Component
const CustomPicker = () => {
const [showValue, toggleView] = useState(false)
const [selectedVal, changeValue] = useState('')
return <>
{selectedVal && <TouchableOpacity onPress={() => changeValue('')}>
<Text>Clear Value</Text>
</TouchableOpacity>}
<View style={styles.pickerView}>
<TouchableOpacity style={styles.placeholderView} onPress={() => toggleView(!showValue)}>
<Text style>{selectedVal || "Select a value..."}</Text>
</TouchableOpacity>
{showValue && <View style={styles.dropDownView}>
<DropDownItem label="Value 1" hideDropdown={toggleView} onPress={val => changeValue(val)} />
<DropDownItem label="Value 2" hideDropdown={toggleView} onPress={val => changeValue(val)} />
<DropDownItem label="Value 3" hideDropdown={toggleView} onPress={val => changeValue(val)} />
</View>}
</View>
</>
}
const App = () => {
return (
<View style={styles.container}>
<CustomPicker />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 40,
alignItems: "center"
},
pickerView: {
width: 160,
height: 30,
padding: 3,
},
placeholderView: {
flex: 1,
backgroundColor: '#e0e0e0',
padding: 3
},
dropDownView: {
position: 'absolute',
top: 32
}
});
export default App;
Link: https://snack.expo.io/MBb60jEQw
Happy Coding !!!

Related

React Native Breadcrumb

I am making a React Native application in which I have menus and submenus.
Menus and submenus structure:
let arr = [
{
name: 'Header 1',
routeName: 'Home',
child: [
{ name: 'Header 1 - Submenu 1', child: [], routeName: 'Home' },
{
name: 'Header 1 - Submenu 2',
child: [],
routeName: 'NotificationScreen',
},
{ name: 'Header 1 - Submenu 3', child: [], routeName: 'Home' },
],
},
{
name: 'Header 2',
routeName: 'NotificationScreen',
child: [
{
name: 'Header 2 - Submenu 1',
child: [],
routeName: 'NotificationScreen',
},
{ name: 'Header 2 - Submenu 2', child: [], routeName: 'Home' },
{
name: 'Header 2 - Submenu 3',
child: [],
routeName: 'NotificationScreen',
},
],
},
];
Render of Menu's and Submenu's:
<TouchableOpacity style={styles.item} onPress={onPress} activeOpacity={1}>
<View style={styles.row}>
<Text style={{ paddingRight: 20 }}>{name}</Text>
{child.length ? <Text>{open ? 'close' : 'open'}</Text> : null}
</View>
{open &&
child.map((x: any, i: any) => {
if (x.child.length) {
return (
<Item
key={x}
active={childActive}
i={i}
setActive={setChildActive}
child={x.child}
/>
);
}
return (
<TouchableOpacity
key={x}
style={styles.subItem}
onPress={() => {
handleRouteChange(x.routeName);
}}>
<Text>
{name} - submenu - {i + 1}
</Text>
</TouchableOpacity>
);
})}
</TouchableOpacity>
Working example: https://snack.expo.dev/#manirajmurugan/custom-header-title-component
Here I am in the need to make a breadcrumb like structure on the screen page as per the navigation done by user through menu and submenus.
Current Scenario:
-> If user clicks on Header 1 and then select submenu Header 1 - Submenu 1, then the user will be redirected to Home Screen.
Expected Scenario:
-> Requirement here is that I am in the need to display a breadcrumb for this screen like,
Header 1 > Header 1 - Submenu 1
On click of the Header 1 in this breadcrumb, user will be redirected to the respective routeName given in the object.
Kindly help me to generate breadcrumb for the navigation done in menu for the respective screen's.
Thanks in advance.
Edit:
In real app menu and submenu will be like,
Here if user click's on Stored Data configuration under Unit Data Management,
then the expected breadcrumb result would be,
Create a piece of state to hold the crumbs. It will be an array that will hold three values: the screen you are currently on, the section title press, and the section item pressed. Handling the last two will be done by the SectionList and to keep track of the current screen you can add a screenListener to the StackNavigator that will listen for all navigation changes on all screens.
import React, { useState, createContext } from 'react';
import { View, StyleSheet, useWindowDimensions } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import Header from './screens/Header';
import HomeScreen from './screens/Home';
import SettingsScreen from './screens/Settings';
const Stack = createNativeStackNavigator();
import { ICON_SIZE, headerHeight } from './Constants';
const initialScreen = 'Settings';
export default function App() {
// this will have at most 3 items:
// the current screen
// the section header
// the section.data[index]
const [crumbNavigation, setCrumbNavigation] = useState([initialScreen]);
const { width, height } = useWindowDimensions();
const screenOptions = {
// pass crumbNavigation and its setter to header
headerTitle: (props) => (
<Header
{...props}
width={width}
height={headerHeight}
crumbNavigation={crumbNavigation}
setCrumbNavigation={setCrumbNavigation}
/>
),
headerStyle: {
height: headerHeight,
width: width,
},
// since there will be a bread crumb navigator
// theres no need for back button
headerBackVisible: false,
headerLeft: () => null,
};
return (
<NavigationContainer>
<Stack.Navigator
initialRouteName={initialScreen}
screenOptions={screenOptions}
screenListeners={{
state: (nav) => {
console.log(nav.type);
const routes = nav.data.state.routes;
const lastRoute = routes[routes.length - 1]?.name;
if (lastRoute)
setCrumbNavigation((prev) => {
prev[0] = lastRoute;
return prev;
});
},
}}>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Settings" component={SettingsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
Now that current screen is handled, you can move on to deal with getting the SectionTitle, which the SectionHeader and MenuItem components handles. If a section data array's length is zero, pressing it will trigger the parent component's onItemPress with the section as an argument, if not, then pressing it will reveal its children
import { useState } from 'react';
import { TouchableOpacity, Text, View, StyleSheet } from 'react-native';
import TouchableMaterialIcon from './TouchableMaterialIcon';
import { ICON_SIZE } from '../Constants';
export default function SectionHeader({ section, toggleSectionMenu, onPress }) {
return (
<TouchableOpacity
style={[
styles.headerContainer,
section.isOpen && styles.highlightedTitleContainer,
]}
onPress={()=>{
if(section.data.length > 0)
toggleSectionMenu(section.id)
else
onPress(section.title)
}}
>
<View style={{ flex: 1 }}>
<Text
styles={[
styles.titleText,
section.isOpen && styles.highlightedTitleText,
]}>
{section.title}
</Text>
</View>
{section.data.length > 0 && (
<TouchableMaterialIcon
name={section.isOpen ? 'keyboard-arrow-up' : 'keyboard-arrow-down'}
size={ICON_SIZE * 0.6}
onPress={() => toggleSectionMenu(section.id)}
/>
)}
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
headerContainer: {
width: '100%',
flexDirection: 'row',
// justifyContent:'center',
alignItems: 'center',
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: '#eee',
paddingVertical: 5,
},
titleText: {
fontSize: 16,
},
highlightedTitleText: {
fontWeight: 'bold',
},
highlightedTitleContainer: {
backgroundColor: '#edf',
},
});
The SectionItem is pretty straightforward. When visible, its a button that when pressed will trigger its grandparent's onItemPressed with both the section title and the item's title
import { View, StyleSheet, Text, TouchableOpacity } from 'react-native';
export default function MenuItem({ section, index, item, onPress }) {
const isLastItem = index == section.data.length - 1;
if (section.isOpen)
return (
<TouchableOpacity
style={[styles.itemContainer, isLastItem && styles.lastItem]}
onPress={() => onPress(section.title, item)}>
<Text>{item}</Text>
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
itemContainer: {
marginRight: 5,
padding: 5,
},
lastItem: {
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: '#eee',
},
});
ButtonWithMenu contains a button that when pressed, renders the SectionList directly beneath it. It accepts an onItemPress prop which will be passed on into the SectionList:
import React, { useState } from 'react';
import {
Text,
View,
StyleSheet,
SectionList,
useWindowDimensions,
Modal,
TouchableWithoutFeedback,
} from 'react-native';
import TouchableMaterialIcon from './TouchableMaterialIcon';
import MenuItem from './MenuItem';
import SectionHeader from './SectionHeader';
import useLayout from '../hooks/useLayout';
export default function DropDownButtonMenu({
name,
size,
color,
onItemPress,
buttonStyle,
containerStyle,
menu,
onMenuAction,
}) {
const [openMenu, setOpenMenu] = useState(false);
const [buttonLayout, onButtonLayout] = useLayout();
// add additional state to menu
const [menuItems, setMenuItems] = useState(
menu?.map((section, i) => {
section.isOpened = false;
section.id = `section-item-${i}`;
return section;
}) || []
);
const { width, height } = useWindowDimensions();
const handleButtonPress = () => {
setOpenMenu((prev) => !prev);
};
const toggleSectionMenu = (sectionId) => {
// deep clone menuItems
const newData = JSON.parse(JSON.stringify(menuItems));
const index = newData.findIndex((section) => section.id == sectionId);
if (index < 0) {
console.log('Section id not found');
return;
}
newData[index].isOpen = !newData[index].isOpen;
setMenuItems(newData);
};
const handleItemPress = (sectionTitle,itemTitle)=>{
onItemPress(sectionTitle,itemTitle)
setOpenMenu(false)
}
return (
<View style={[containerStyle, { zIndex: 1 }]}>
<TouchableMaterialIcon
style={buttonStyle}
name={name}
size={size}
color={color}
onLayout={onButtonLayout}
onPress={handleButtonPress}
disabled={menuItems.length < 1}
/>
{/*
wrap modal in touchable so that pressing outside modal will close it
tried to use absolute positioned view but no matter the zIndex but
the screen contents would always appear on top
*/}
<TouchableWithoutFeedback onPress={() => setOpenMenu(false)}>
<Modal transparent visible={openMenu}>
<View
style={[
styles.menu,
{
top: buttonLayout.y + buttonLayout.height,
left: buttonLayout.left,
minWidth: 150,
maxHeight: height * 0.6,
},
]}>
<SectionList
sections={menuItems}
renderItem={(props) => <MenuItem {...props} onPress={handleItemPress} />}
renderSectionHeader={(props) => (
<SectionHeader
{...props}
toggleSectionMenu={toggleSectionMenu}
onPress={handleItemPress}
/>
)}
/>
</View>
</Modal>
</TouchableWithoutFeedback>
</View>
);
}
const styles = StyleSheet.create({
menu: {
position: 'absolute',
backgroundColor: 'white',
padding: 10,
zIndex: 10,
},
});
Now in the Header component the only thing that is left to do is create a list for the SectionList to render and then update the crumb state with onItemPress:
import { useContext } from 'react';
import { View, StyleSheet, Text, useWindowDimensions } from 'react-native';
import ButtonWithMenu from '../components/ButtonWithMenu';
import { LinearGradient } from 'expo-linear-gradient';
import { ICON_SIZE } from '../Constants';
export default function Header({width,height,crumbNavigation,setCrumbNavigation}) {
return (
<View style={{flex:1,height, width}}>
<View style={styles.navbar}>
<ButtonWithMenu
containerStyle={[styles.navbarButton,{marginLeft:ICON_SIZE}]}
name="home"
size={ICON_SIZE}
color="black"
/>
<ButtonWithMenu
containerStyle={styles.navbarButton}
name="close"
size={ICON_SIZE}
color="black"
onItemPress={(sectionTitle, itemTitle) =>
setCrumbNavigation((prev) => {
const newCrumbNav = [prev[0]];
if (sectionTitle) newCrumbNav.push(sectionTitle);
if (itemTitle) newCrumbNav.push(itemTitle);
return newCrumbNav;
})
}
menu={[
{ title: 'Disconnect from Unit', data: [] },
{ title: 'Monitor Unit', data: ['This Thing', 'That Thing'] },
{ title: 'Unit Settings', data: ['This Thing', 'That Thing'] },
{
title: 'Unit Data Management',
data: ['Stored Data Configuration', 'Stored Data Snapshot'],
},
{ title: 'Information', data: ['This Thing', 'That Thing'] },
{ title: 'Help', data: ['This Thing', 'That Thing'] },
]}
/>
</View>
<LinearGradient
colors={['#902337', '#21458d']}
style={styles.colorBar}
start={{ x: 1, y: 1 }}
locations={[0.5, 0.8]}
/>
<View style={styles.crumbs}>
<Text style={styles.crumbScreen} numberOfLines={1}>
{crumbNavigation[0]} {crumbNavigation.length > 1 && ' > '}
<Text style={styles.crumbTitle}>
{crumbNavigation.slice(1).join(' : ')}
</Text>
</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
navbar: {
flexDirection: 'row',
},
colorBar: {
height: 5,
width: '100%',
},
navbarButton: {
// marginHorizontal: 10,
paddingHorizontal: ICON_SIZE * 0.25,
},
crumbs: {
overflow:'hidden',
flexWrap:'none'
},
crumbScreen: {
fontWeight: 'bold',
},
crumbTitle: {
color: '#21458d',
fontWeight: '400',
},
});
Demo
For readability, I started by moving all of the components into their own separate files. I also used a FlatList instead of a ScrollView for the recursive SubMenuItem rendering.
I first broke the breadcrumb down into three components. The first, MenuItem, which would always be visible in the Header. When pressed, it would reveals a dropdown menu, which would reveal the SubMenu, MenuItem's children. Pressing SubMenu would reveal its children, if it had any, or would trigger navigation, if a routeName was provided. Demo

React Native: Why does FlatList re-render completely on data changes?

thanks for reading my question! I am struggling with this problem since a few days now: My Flatlist component re-renders all items in the list every time I make a change to the underlying data.
Situation:
I have a FlatList component rendering Items which contain a TouchableOpacity object to toggle Favorite status on this item.
If this button is pressed, I expect only this specific item to change/re-render in my FlatList instead of all items. It feels like as soon as I update state by calling setListData, it re-renders everything.
I have encountered this issue in a more complex setup but was able to drill it down to this core problem. Or is this actually the expected behavior?
Code:
import React, { useState } from "react";
import {
View,
Text,
StyleSheet,
FlatList,
TouchableOpacity,
} from "react-native";
const PlanerScreen = () => {
const [listData, setListData] = useState([
{ id: "1", name: "Banana", isFav: true },
{ id: "2", name: "Apple", isFav: false },
]);
const Item = ({ item, onPressHandler }) => {
console.log(item.name, " rendered");
const color = item.isFav ? "red" : "green";
return (
<View
style={{
flexDirection: "row",
width: "100%",
margin: 10,
}}
>
<Text>{item.name}</Text>
<TouchableOpacity
style={{ width: 100, height: 50, backgroundColor: color }}
onPress={onPressHandler}
/>
</View>
);
};
const favHandler = (id) => {
setListData(
listData.map((item) =>
item.id === id ? { ...item, isFav: !item.isFav } : item
)
);
};
console.log("FlatList rendered");
return (
<View style={{ flex: 1 }}>
<StatusBar style={selectedTheme === "light" ? "dark" : "light"} />
<FlatList
data={listData}
renderItem={({ item }) => (
<Item item={item} onPressHandler={() => favHandler(item.id)} />
)}
keyExtractor={(item) => item.id}
/>
</View>
);
};
export default PlanerScreen;
Console Output on clicking the Favorite Toggle Button:
FlatList rendered
Banana rendered
Apple rendered
FlatList rendered
Banana rendered
Apple rendered
FlatList rendered
Banana rendered
Apple rendered
You can use React.memo which is an alternative to shouldComponentUpdate for functional components.
It tells React when to re-render the component based on prev and next props.
import React, { useState, useCallback } from "react";
import {
View,
Text,
StyleSheet,
FlatList,
TouchableOpacity,
} from "react-native";
const styles = StyleSheet.create({
container: {
flex: 1,
}
})
const keyExtractor = (item) => item.id;
const Item = React.memo(({ item, onPressHandler }) => {
console.log(item.name, " rendered");
const color = item.isFav ? "red" : "green";
return (
<View
style={{
flexDirection: "row",
width: "100%",
margin: 10,
}}
>
<Text>{item.name}</Text>
<TouchableOpacity
style={{ width: 100, height: 50, backgroundColor: color }}
onPress={() => onPressHandler(item.id)}
/>
</View>
);
}, (prevProps, nextProps) => {
if (prevProps.item.isFav === nextProps.item.isFav) return true;
return false;
});
const PlanerScreen = () => {
const [listData, setListData] = useState([
{ id: "1", name: "Banana", isFav: true },
{ id: "2", name: "Apple", isFav: false },
]);
const favHandler = useCallback((id) => {
setListData(prevState => {
return prevState.map((item) =>
item.id === id ? { ...item, isFav: !item.isFav } : item
)
}
);
}, []);
console.log("### FlatList rendered #####");
return (
<View style={styles.container}>
<FlatList
data={listData}
renderItem={({ item }) => <Item item={item} onPressHandler={favHandler} />}
keyExtractor={keyExtractor}
/>
</View>
);
};
export default PlanerScreen;

React, render different components and maintain scroll position

Suppose you have a horizontal flatlist.
When a user clicks a button in an item, you want to present a view which looks different from the flat-list item you had.
Suppose you implement it like the following
{showDetail ? (
<DetailView onPress={toggleShowDetail} />
) : (
<FlatList
data={data}
renderItem={() => (
<View>
<Button onPress={toggleShowDetail} />{' '}
</View>
)}
/>
)}
Is the scroll position of flatlist maintained when the flatlist is replaced with DetailView and replaced back?
if not, what are the approaches I can take?
I'd like to avoid using modal if possible
edit,
I'm not sure if setting style width=0 would maintain the scroll position when set width=prevSavedWidth .. but definately can try..
import _ from 'lodash'
import React, {useState} from 'react'
import {useDispatch} from 'react-redux'
import {useSelector} from 'react-redux'
import {
Text,
Image,
View,
NativeModules,
NativeEventEmitter,
TouchableOpacity,
FlatList,
} from 'react-native'
const Qnas = props => {
const flatlistRef = React.useRef(null)
const [single, setSingle] = React.useState(false)
let qnas = [
{
title: 'a',
id: 1,
},
{
title: 'b',
id: 2,
},
{
title: 'c',
id: 3,
},
{
title: 'd',
id: 4,
},
{
title: 'e',
},
{
title: 'f',
},
{
title: 'j',
},
]
const toggle = () => {
setSingle(!single)
}
const renderItem = ({item: qna, index}) => {
return (
<View style={{height: 80, width: 200}}>
<Text>{qna.title}</Text>
<TouchableOpacity onPress={toggle}>
<Text>toggle</Text>
</TouchableOpacity>
</View>
)
}
const keyExtractor = (item, index) => {
return `qna-${item.title}-${index}`
}
return (
<View style={{height: 200}}>
{single ? (
<View>
<Text>hello</Text>
<TouchableOpacity onPress={toggle}>
<Text>toggle</Text>
</TouchableOpacity>
</View>
) : (
<FlatList
horizontal
ref={flatlistRef}
data={qnas}
renderItem={renderItem}
keyExtractor={keyExtractor}
contentContainerStyle={{
flexDirection: 'column',
flexWrap: 'wrap',
}}
/>
)}
</View>
)
}
export default Qnas
the questions is not clear, but the scroll position of the page is always maintained , even if you render your components on conditional basis. if you want to make sure that you always scroll to the top of the page when you show the Detail view , you can always do window.scrollTo(0, 0 before showDetail flag as true.
Kindly provide more details for better understanding or share a code pen
you can have a handleScroll method which gets called on FlatList Scroll and saves the srollPosition in state
const handleScroll = event => {
console.log(event);
setScrollPosition(event.nativeEvent.contentOffset.x);
};
<FlatList onScroll={handleScroll} />```
and then in your toggle method have a check on if single is true set the scrollPosition of the FlatList using ref
const toggle = () => {
if(single){
this.flatlistRef.scrollToOffset({ animated: true, offset: scrollPosition }
setSingle(!single);
}
hope this helps

I keep getting this error. TypeError: addItems is not a function. (In 'addItems(text)', 'addItems' is an instance of Object)

This is the error I get every time I try and add something to my list.
TypeError: addItems is not a function. (In 'addItems(text)', 'addItems' is an instance of Object)
I cannot figure out what I am doing wrong. Im new to react-native so any help would be greatly appreciated.
Here is my App.js
import React, { useState } from 'react';
import { View, Text, StyleSheet, ImageBackground, FlatList } from 'react-native';
import 'react-native-get-random-values';
import { v4 as uuidv4 } from 'uuid';
import { uuid } from 'uuidv4';
import Header from './Componets/Header';
import AddItem from './Componets/AddItem';
import background from './Images/sunrise-in-the-smoky-mountains.jpg';
import ListItem from './Componets/ListItem';
const App = () => {
const [item, setItems] = useState([
// {
// id: uuidv4(),
// name: ''
// },
{
id: uuidv4(),
name: "gym"
},
{
id: uuidv4(),
name: "study"
}
]);
const addItems = (text) => {
setItems(prevItems => {
return [{ id: uuidv4(), text }, ...prevItems]
})
}
const deleteItem = (id) => {
setItems(prevVal => {
return prevVal.filter(item => item.id != id)
})
}
return (
<View style={styles.container}>
<ImageBackground source={background} style={styles.image}>
<Header
title="Gotta get this done!" />
<AddItem
addItem={addItems}
/>
<FlatList
data={item}
renderItem={({ item }) => (
<ListItem item={item.name} deleteItem={deleteItem} />
)}
/>
</ImageBackground>
</View>
)
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
image: {
flex: 1,
resizeMode: "cover",
justifyContent: "center"
}
})
export default App;
Here is where I call the function and get the error.
import React, { useState } from 'react';
import { View, Text, StyleSheet, TextInput, TouchableOpacity, Button } from 'react-native';
const AddItem = ( addItems ) => {
const [text, setText] = useState("");
const onChange = (inputVal) => setText(inputVal);
return (
<View style={styles.addItemView}>
<TextInput
style={styles.inputText}
placeholder="Add item to list..."
onChangeText={onChange}
/>
<TouchableOpacity style={styles.button}>
<Button title="Add Item" onPress={() => addItems(text)} />
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
addItemView: {
flex: 1,
flexDirection: "row",
alignItems: 'center'
},
inputText: {
fontSize: 20,
backgroundColor: "white",
alignItems: 'center',
justifyContent: 'center',
borderWidth: 1,
width: 250,
},
button: {
alignItems: "center",
justifyContent: "center",
height: 40,
backgroundColor: "#bbc7ad",
borderRadius: 10,
borderWidth: 2,
borderColor: "#99a191",
marginLeft: 20,
}
})
export default AddItem;
You are passing addItems function as a prop in
<AddItem
addItem={addItems}
/>
When you pass any function or value to any functional component in React you can access them only via props so to access addItems you need to access this function from the props
You can do that by following ways
Method 1
const AddItem = ( props ) => {
// We are extracting addItem function from props
const {addItem} = props
const [text, setText] = useState("");
const onChange = (inputVal) => setText(inputVal);
return (
<View style={styles.addItemView}>
<TextInput
style={styles.inputText}
placeholder="Add item to list..."
onChangeText={onChange}
/>
<TouchableOpacity style={styles.button}>
<Button title="Add Item" onPress={() => addItem(text)} />
</TouchableOpacity>
</View>
);
};
Method 2 :
const AddItem = ({addItem} ) => {
.....
return (
<View style={styles.addItemView}>
......
<TouchableOpacity style={styles.button}>
<Button title="Add Item" onPress={() => addItem(text)} />
</TouchableOpacity>
</View>
);
};
This seems to work for now. Still unclear as to why using destructuring in my original version didnt work. Please chime in if you can help with that. Thanks!
const AddItem = (props) => {
const [text, setText] = useState("");
const onChange = inputVal => setText(inputVal);
return (
<View style={styles.addItemView}>
<TextInput
style={styles.inputText}
placeholder="Add item to list..."
onChangeText={onChange}
/>
<TouchableOpacity style={styles.button}>
<Button title="Add Item" onPress={() => props.addItem(text)} />
</TouchableOpacity>
</View>
);
};

React native how to animate view opening up->down

Consider the following component where the user selects an option from a list:
import React, { Component } from "react";
import PropTypes from "prop-types";
import {
View,
Text,
StyleSheet,
Platform,
FlatList,
TouchableNativeFeedback,
TouchableOpacity,
PLatform
} from "react-native";
import Icon from "react-native-vector-icons/Ionicons";
import { colors, metrics } from "../../themes";
const Touchable =
Platform.OS === "android" ? TouchableNativeFeedback : TouchableOpacity;
class MenuSelector extends Component<{
onSelect: () => any,
config: object,
selected: string
}> {
state = {
listOpened: false
};
handlePress = id => {
this.props.onPress(id);
};
handleSelect = id => {
if (this.props.onSelect) this.props.onSelect(id);
this.setState({
listOpened: false
});
};
handleMenu = () => {
this.setState({
listOpened: !this.state.listOpened
});
};
render = () => {
let title = "";
if (this.props.config) {
title = this.props.config[0].title;
if (this.props.selected) {
let found = this.props.config.find(item => {
return item.id === this.props.selected;
});
if (found) title = found.title;
}
}
let top = (
<View style={styles.header}>
<Text style={styles.text}>{title}</Text>
<Touchable>
<Text style={styles.text}>
<Icon
name={"ios-menu"}
size={20}
onPress={this.handleMenu}
/>
</Text>
</Touchable>
</View>
);
let list = null;
if (this.state.listOpened === true) {
list = (
<FlatList
data={this.props.config}
renderItem={({ item }) => (
<Touchable onPress={this.handleSelect}>
<Text style={[styles.text, styles.listItem]}>{item.title}</Text>
</Touchable>
)}
/>
);
}
return (
<View style={styles.container}>
{top}
{list}
</View>
);
};
}
export default MenuSelector;
const styles = StyleSheet.create({
container: {
flex: -1,
flexDirection: "column"
},
header: {
flex: -1,
flexDirection: "row",
justifyContent: "space-between",
padding: 10,
backgroundColor: "blue"
},
text: {
fontSize: 16,
color: "white",
textAlign: "center",
fontWeight: "bold"
},
listItem: {
padding: 10,
backgroundColor: "blue"
}
});
The component is used in the following context:
let config = [
{
title="Option 1",
id="option1"
},
{
title="Option 2",
id="option2"
},
{
title="Option 3",
id="option3"
},
{
title="Option 4",
id="option4"
},
];
return (
<View style={styles.container}>
<MenuSelector
config={config.options}
selected={this.state.mode}
onPress={this.handleButtonListPress}
/>
<FlatList
data={this.props.data}
keyExtractor={(item, index) => index.toString()}
renderItem={({ item }) => (
<Text style={styles.text}>{item.name}</Text>
)}
/>
</View>
);
As it is, the <MenuSelector> component appears "at once" on screen. I need to add an sliding effect to <MenuSelector>, "pushing down" the data FlatList when appearing on screen...
On closing, same behaviour, but animating from down to up.
How can I add such animation behaviour to my MenuSelector component ?

Resources