I am following the tutorial in the link: https://medium.com/appandflow/react-native-scrollview-animated-header-10a18cb9469e .
However I can't seem to understand how to add tabs to this such that the tab headers get fixed to top when scrolled up. Can anyone please suggest how to achieve this?
I was able to achieve it using ScrollableTab and Tab in native-base library.
Code looks like this
<Tabs
prerenderingSiblingsNumber={3}
onChangeTab={({ i }) => {
this.setState({ height: this.heights[i], activeTab: i })
}}
renderTabBar={(props) => (
<Animated.View style={{ transform: [{ translateY: tabY }], zIndex: 1, width: "100%", backgroundColor: "white", paddingTop: HEADER_MAX_HEIGHT }}>
<ScrollableTab
{...props}
renderTab={(name, page, active, onPress, onLayout) => (
<TouchableOpacity key={page}
onPress={() => onPress(page)}
onLayout={onLayout}
activeOpacity={0.4}>
<Animated.View
style={{
flex: 1,
height: 100,
backgroundColor: tabBg
}}>
<TabHeading scrollable
style={{
backgroundColor: "transparent",
width: Dimensions.get('window').width / 2
}}
active={active}>
<Animated.Text style={{
fontWeight: active ? "bold" : "normal",
color: 'black',
padding: 10,
fontSize: active ? 20 : 18
}}>
{name}
</Animated.Text>
</TabHeading>
</Animated.View>
</TouchableOpacity>
)}
underlineStyle={{ backgroundColor: 'black' }}
/>
</Animated.View>
)}>
<Tab heading="Tab 1">
{this.tabContent(30, 0)}
</Tab>
<Tab heading="Tab 2">
{this.tabContent(15, 1)}
</Tab>
</Tabs>
use this:
expo install react-native-gesture-handler react-native-reanimated
Then basic usage look like this to replace in <Animated.View ......<Text>....</Text>..... ></Animated.View>:
<TabView
navigationState={{ index, routes }}
onIndexChange={setIndex}
renderScene={SceneMap({
first: FirstRoute,
second: SecondRoute,
})}
/>
I hope it'll help you..!
In case anybody else falls on this thread, I developed a new package, react-native-animated-screen, that does exactly what you need
Check it out
https://www.npmjs.com/package/react-native-animated-screen
import React from 'react';
import { Image, Text, View } from 'react-native';
import AnimatedScreen from 'react-native-animated-screen';
const Component = () => {
return (
<AnimatedScreen.Wrapper>
<AnimatedScreen.Header>
<View>
<Text>Title</Text>
<AnimatedScreen.CollapsibleElement>
<Text>Subtitle</Text>
</AnimatedScreen.CollapsibleElement>
<AnimatedScreen.Element>
<YourTabsComponen />
</AnimatedScreen.Element>
</View>
</AnimatedScreen.Header>
<AnimatedScreen.ScrollView>
<View style={{ height: '300%' }}>
<View>
<Text>Body</Text>
</View>
</View>
</AnimatedScreen.ScrollView>
</AnimatedScreen.Wrapper>
);
};
In the example above only the title and YourTabBComponentare going to remain after scrolling, the subtitle (as all the elements wrapped in a CollapsibleElement) will disappear.
Ideally you could also have the tabs to appear only when entirely scrolled using the interpolate prop or the animatedStyle of the AnimatedScreen.Element
// using interpolate the animation will flow from 0 to scrollY === headerMaxHeight
<AnimatedScreen.Element interpolate={{ opacity: [0, 1], height: [0, 60] }}>
<TabComponent />
</AnimatedScreen.Element>
// alternatevely you can have more control with an animatedStyle
<AnimatedScreen.Element animatedStyle={scrollY => ({
opacity: scrollY.interpolate({
inputRange: [100, 200],
outputRange: [0, 1]
extrapolate: 'clamp'
})
})}>
<TabComponent />
</AnimatedScreen.Element>
In case anybody else falls on this thread, I developed a new package, react-native-animated-screen, that does exactly what you need
Check it out
https://www.npmjs.com/package/react-native-animated-screen
import React from 'react';
import { Image, Text, View } from 'react-native';
import AnimatedScreen from 'react-native-animated-screen';
const Component = () => {
return (
<AnimatedScreen.Wrapper>
<AnimatedScreen.Header>
<View>
<Text>Title</Text>
<AnimatedScreen.CollapsibleElement>
<Text>Subtitle</Text>
</AnimatedScreen.CollapsibleElement>
<AnimatedScreen.Element>
<YourTabsComponen />
</AnimatedScreen.Element>
</View>
</AnimatedScreen.Header>
<AnimatedScreen.ScrollView>
<View style={{ height: '300%' }}>
<View>
<Text>Body</Text>
</View>
</View>
</AnimatedScreen.ScrollView>
</AnimatedScreen.Wrapper>
);
};
In the example above only the title and YourTabBComponentare going to remain after scrolling, the subtitle (as all the elements wrapped in a CollapsibleElement) will disappear.
Ideally you could also have the tabs to appear only when entirely scrolled using the interpolate prop or the animatedStyle of the AnimatedScreen.Element
// using interpolate the animation will flow from 0 to scrollY === headerMaxHeight
<AnimatedScreen.Element interpolate={{ opacity: [0, 1], height: [0, 60] }}>
<TabComponent />
</AnimatedScreen.Element>
// alternatevely you can have more control with an animatedStyle
<AnimatedScreen.Element animatedStyle={scrollY => ({
opacity: scrollY.interpolate({
inputRange: [100, 200],
outputRange: [0, 1]
extrapolate: 'clamp'
})
})}>
<TabComponent />
</AnimatedScreen.Element>
Related
First of all I would like to mention that the code works fine on iOS but not on Android.
I'm trying to make my own custom dropdown list.
When you pressing on Input the Dropdown opens just beneath it with position absolute.
You can play around with it here: https://snack.expo.dev/#eko_test/dropdown
and see example snippets below.
<Input
value={inputValue}
placeholder={placeholder}
onTouchStart={() => setShowItems((prevState) => !prevState)}
onTouchEnd={() => Keyboard.dismiss()}
onChangeText={onSearchItem}
/>
{showItems && (
<ScrollView
style={styles.itemsContainer}
contentContainerStyle={{ padding: 6 }}
keyboardShouldPersistTaps="always"
>
{usedItemList.length > 0 ? (
<View>
<Text style={styles.hintText}>Last used</Text>
<DropdownList
items={savedItemList}
onItemSelect={onListItemSelect}
/>
<View style={styles.separator} />
</View>
) : undefined}
<DropdownList items={itemList} onItemSelect={onListItemSelect} />
</ScrollView>
)}
const DropdownList: FC<DropdownListProps> = ({ items, onItemSelect }) => {
return (
<View>
{items.map((item) => (
<DropdownItemComponent
key={item.id}
item={item}
onItemPress={() => onItemSelect(item)}
/>
))}
</View>
);
};
itemsContainer: {
position: "absolute",
top: 35,
width: "100%",
backgroundColor: Colors.black,
borderBottomWidth: 1.6,
borderBottomColor: Colors.green,
maxHeight: 160,
},
I've created a custom dropdown using TouchOpacity component of react native as follows.
<View style={dropDownStyle}>
<TouchableOpacity onPress={() => _switchTimeSpan('Day')}>
<Text style={dropDownItemStyle}>Day</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => _switchTimeSpan('Week')}>
<Text style={dropDownItemStyle}>Week</Text>
</TouchableOpacity>
</View>
The style is as follows.
dropDownStyle: {
position: 'absolute',
marginTop: 20,
width: 80,
},
dropDownItemStyle: {
marginTop: 5,
flex: 1,
textAlign: 'right',
},
When pressed the TouchOpacity component doesn't trigger the onpress function. This issue only exists in android and not IOS.
Edit 1 : There is a areachart created use react-native-svg-charts which is being overlapped by the mentioned dropdown. However upon inspecting if the reason for the onPress not working could be because of zIndex issues i noticed that the mentioned dropdown is the top most component.
The code for the chart is the following.
I am using react-native-svg-charts
<View style={containerStyle}>
<YAxis
data={data}
style={yAxisStyle}
formatLabel={value => yAxisFormat(value)}
contentInset={verticalContentInset}
numberOfTicks={5}
svg={axesSvg}
/>
<View style={chartWrapperStyle}>
<AreaChart
style={chartStyle}
data={data}
contentInset={verticalContentInset}
curve={shape.curveCatmullRom}
svg={{ fill: '#FF4D4D' }}
animate
/>
<View style={xAxisStyle}>
{
timeSpan !== 'Month' && (
<XAxis
data={data}
// formatLabel={(value, index) => months[value]}
formatLabel={(value, index) => xAxisPoints[index]}
contentInset={{ left: 10, right: 10 }}
// numberOfTicks={5}
svg={axesSvg}
/>
)
}
</View>
</View>
</View>
The style for the chart is as follows.
containerStyle: {
height: 200,
paddingLeft: 20,
paddingRight: 20,
flexDirection: 'row',
},
yAxisStyle: {
// marginBottom: 20,
position: 'absolute',
height: 180,
left: 20,
zIndex: 2,
},
chartStyle: {
flex: 1,
},
chartWrapperStyle: {
flex: 1,
},
xAxisStyle: {
marginHorizontal: -5,
height: 20,
},
When I'm testing this as isolated and only component on screen everything seems to work properly on Android (Samsung Galaxy Tab 2). Try to isolate this component and see if it will work for you on Android, maybe other components affect it. Also you could try to check if container component (with dropDownStyle) has some height or try to set 100%.
I have tried using a FlatList and a map function to generate a list of entries, but I am getting random lines between the entries (see the blue part of my screenshot)
What is causing these and how can I remove them?
Here is my FlatList:
<FlatList
data={TriageTransfertData[0].content[0].content}
renderItem={({ item }) => (
<View style={styles.subentryContainer}>
<View style={styles.ttEntryFirst} />
<View style={styles.ttEntryContentSub}>
<Text style={styles.ttTextSub}>{item.text}</Text>
</View>
</View>
)}
keyExtractor={item => item.text} />
And here is the styling:
subentryContainer: {
flexDirection: 'row',
width: '100%',
},
ttEntryFirst: {
width: '2%',
backgroundColor: Colors.Blue
},
ttEntryContentSub: {
width: '98%',
justifyContent: 'center',
paddingLeft: responsiveWidth(2),
paddingTop: 10,
paddingBottom: 10,
borderTopWidth: 1,
borderColor: Colors.GreyLight
},
And finally, here is a screenshot (notice the unwanted line in the blue area):
I think you're talking about ItemSeparatorComponent. It's rendered by default in a FlatList, but you can override it passing a custom component or a blank code function.
Here is the brief doc.
Hope this helps!
I am learning React Native programming for Android mobile apps. I am making a screen where I need to set height of button. I have added button in view and set the height of using style however there is no change on button height.
/**
* LoginComponent of Myntra
* https://github.com/facebook/react-native
* #flow
*/
import React, { Component } from "react";
import { AppRegistry, Text, View, Button, TextInput } from "react-native";
class LoginComponent extends Component {
render() {
return (
<View style={{ flex: 1, flexDirection: "column", margin: 10 }}>
<TextInput
style={{
height: 40,
borderColor: "gray",
borderWidth: 0.5
}}
placeholder="Email address"
underlineColorAndroid="transparent"
/>
<TextInput
style={{
height: 40,
borderColor: "gray",
borderWidth: 0.5
}}
placeholder="Password"
secureTextEntry={true}
underlineColorAndroid="transparent"
/>
<View style={{ height: 100, marginTop: 10 }}>
<Button title="LOG IN" color="#2E8B57" />
</View>
</View>
);
}
}
AppRegistry.registerComponent("Myntra", () => LoginComponent);
Can anyone help me to set the height of button according to my requirement?
This component has limited options, so you can't resize it to a fixed height.
I recommend you to use the TouchableOpacity component to build your own button, with own properties and styles.
You can easily style it like this:
<TouchableOpacity style={{ height: 100, marginTop: 10 }}>
<Text>My button</Text>
</TouchableOpacity>
You can set the button width as per the mentioned width easily by using following method :
<View style={[{ width: "90%", margin: 10, backgroundColor: "red" }]}>
<Button
onPress={this.buttonClickListener}
title="Button Three"
color="#FF3D00"
/>
</View>
Best solution is to use minHeight or maxHeight instead of using Height const.
It often happens that we want to change the dimensions of the button, which by default is extended to the entire width of the parent element. While reducing its width is not a problem – it is enough to reduce the width of the parent, but changing the height is already problematic. The Button element has no style property, so apart from changing the text color on iOS and the background color on Android, we can not set much in it.
To have more control over the button, it is better to use TouchableOpacity or TouchableNativeFeedback instead.
TouchableOpacity Function Component Example -
import React, { useState } from "react";
import { StyleSheet, Text, TouchableOpacity, View } from "react-native";
const App = () => {
const [count, setCount] = useState(0);
const onPress = () => setCount(prevCount => prevCount + 1);
return (
<View style={styles.container}>
<View style={styles.countContainer}>
<Text>Count: {count}</Text>
</View>
<TouchableOpacity
style={styles.button}
onPress={onPress}
>
<Text>Press Here</Text>
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
paddingHorizontal: 10
},
button: {
alignItems: "center",
backgroundColor: "#DDDDDD",
padding: 10
},
countContainer: {
alignItems: "center",
padding: 10
}
});
export default App;
<View style={styles.btnContainer}>
<TouchableOpacity>
<Button style={styles.btnSize}>
<Text>Change Address</Text>
</Button>
</TouchableOpacity>
<TouchableOpacity>
<Button style={styles.btnSize}>
<Text>Change Address</Text>
</Button>
</TouchableOpacity>
</View>
Style sheet code snippet
const styles = StyleSheet.create({
btnContainer:{
flexDirection:"row",
justifyContent:"space-between"
},
btnSize:{
width:"100%"
}
})
The component Button supports a minimal level of customization, so you have to use an other component.
You can use : Pressable or TouchableOpacity ,
<Pressable onPress={onPressFunction} style={styles.yourButtonStyle}>
<Text>I'm pressable!</Text>
</Pressable
const styles = StyleSheet.create({
yourButtonStyle: {
...
}
});
Doc Button
I want to achieve a behavior like android's CoordinatorLayout enter always for my ToolBar i tried too many solutions some did work but not fully like https://github.com/maolion/mao-rn-android-kit which is really cool but with one setback as it doesn't work with ListView i also tried Animated but the scroll event throttle on android is just not working most of the times it does not even work.
Using mao-rn-android-kit
<CoordinatorLayoutAndroid ref={(component) => this.coordinatorLayout = component} fitsSystemWindows={false}>
<AppBarLayoutAndroid
layoutParams={{
width: 'match_parent',
height: 112
}}
style={{ backgroundColor:"#528eff" }}>
<View layoutParams={{height: 56, width: this.windowWidth, scrollFlags: (
AppBarLayoutAndroid.SCROLL_FLAG_SCROLL |
AppBarLayoutAndroid.SCROLL_FLAG_ENTRY_ALWAYS)}} style={{height: 56}}>
<ToolbarAndroid
titleColor={'#FFF'}
title={this.props.title}
navIcon={images.arrowBack}
onIconClicked={() => this._goBack()}
onActionSelected={() => {}}
actions={[{title: 'Search', icon: images.search, show: 'always'}]}
style={[{backgroundColor: '#528eff', width: this.windowWidth, height: 56}]}/>
</View>
<View layoutParams={{height: 56, width: this.windowWidth}}
style={{flex: 0, flexDirection: 'row', justifyContent: 'center', width: this.windowWidth, backgroundColor: '#528eff'}}>
<TouchableOpacity onPress={() => this.getDocuments('high')}
style={[styles.highNormalLowDocListHeaderStateTextContainer, highSelected.borderStyle]}>
<Text
style={[styles.highNormalLowDocListHeaderStateText, highSelected.textStyle]}>HIGH</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.getDocuments('normal')}
style={[styles.highNormalLowDocListHeaderStateTextContainer, normalSelected.borderStyle]}>
<Text
style={[styles.highNormalLowDocListHeaderStateText, normalSelected.textStyle]}>NORMAL</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.getDocuments('low')}
style={[styles.highNormalLowDocListHeaderStateTextContainer, lowSelected.borderStyle]}>
<Text
style={[styles.highNormalLowDocListHeaderStateText, lowSelected.textStyle]}>LOW</Text>
</TouchableOpacity>
</View>
</AppBarLayoutAndroid>
<View
ref={(component) => this.contentLayout = component}
style={{flex: 1, backgroundColor: 'transparent', height: this.windowHeight - 150}}>
<ListView
style={{height: this.windowHeight - 150, overflow: 'hidden'}}
dataSource={this.state.documents}
enableEmptySections={true}
renderRow={(rowData) => this._renderRow(rowData)}
/>
</View>
</CoordinatorLayoutAndroid>
The key to reacting to the scroll position fluidly is using Animated.event along with the onScroll to update an Animated.value
getInitialState: function() {
return {
scrollY: new Animated.Value(0)
}
},
render() {
return (
<ScrollView
scrollEventThrottle={16}
onScroll={Animated.event(
[{nativeEvent:
{contentOffset:
{y: this.state.scrollY}
}
}]
)}>
// etc ...
}
I could then call interpolate on this.state.scrollY and feed this value into a transform style on another component that I wanted to update as the ScrollView scrolled.