I have cobbled together a working version of a Microsoft Excel like "freeze pains" view. The column header scrolls with the content horizontally and the row headers scroll with the content vertically but each is "stuck" in position when the other is scrolled.
You can try the working version here.
It's not optimal as it stutters if you stop a flicked scroll or just swipe around a lot.
The approach uses a couple techniques but the one causing the issue is the synced scroll view.
As outlined here, I've tried setting useNativeDriver: true, which necessitates changing
ScrollView to Animated.ScrollView and
ref={ref => (this.instance = ref)} to ref={ref => (this.instance = ref._component)}
but then the synced goes completely haywire.
I'd love ideas on a more optimal approach. How can this be improved?
import React from 'react';
import { ScrollView, Animated, Text, View } from 'react-native';
export default class SyncScrollTest extends React.Component {
constructor() {
super();
this.scrollPosition = new Animated.Value(0);
this.scrollEvent = Animated.event(
[{ nativeEvent: { contentOffset: { y: this.scrollPosition } } }],
{ useNativeDriver: false },
);
}
render() {
return (
<View style={{ flex: 1 }}>
<View style={{ flexDirection: 'row' }}>
<ScrollViewVerticallySynced
style={{ width: 50, marginTop: 60 }}
name="C1"
color="#F2AFAD"
onScroll={this.scrollEvent}
scrollPosition={this.scrollPosition}
/>
<ScrollView horizontal bounces={false}>
<View style={{ width: 600 }}>
<View style={{ height: 60, justifyContent: 'center', backgroundColor: '#B8D2EC' }}>
<Text>
I am Column Header!! I am Column Header!! I am Column Header!! I am Column
Header!! I am Column Header!! I am Column Header!! I am Column Header!!
</Text>
</View>
<ScrollViewVerticallySynced
style={{ width: 600 }}
name="C2"
color="#D9E4AA"
onScroll={this.scrollEvent}
scrollPosition={this.scrollPosition}
/>
</View>
</ScrollView>
</View>
</View>
);
}
}
class ScrollViewVerticallySynced extends React.Component {
componentDidMount() {
this.listener = this.props.scrollPosition.addListener((position) => {
this.instance.scrollTo({
y: position.value,
animated: false,
});
});
}
render() {
const { name, color, style, onScroll } = this.props;
return (
<ScrollView
key={name}
ref={ref => (this.instance = ref)}
style={style}
scrollEventThrottle={1}
onScroll={onScroll}
bounces={false}
showsVerticalScrollIndicator={false}
>
{someRows(name, 25, color)}
</ScrollView>
);
}
}
const someRows = (name, rowCount, color) =>
Array.from(Array(rowCount).keys()).map(index =>
(<View
key={`${name}-${index}`}
style={{
height: 50,
backgroundColor: index % 2 === 0 ? color : 'white',
flex: 1,
alignItems: 'center',
justifyContent: 'center',
}}
>
<Text>
{name} R{index + 1}
</Text>
</View>),
);
```
I've changed your example, instead of using listeners and Animated Event I use the scrollTo method from ScrollView to synchronize the scrolling. I think that listeners are the cause of lag between the rows when you are scrolling.
You can test the changes here.
import React from 'react';
import { ScrollView, Text, View } from 'react-native';
import { Constants } from 'expo'
export default class SyncScrollTest extends React.Component {
constructor() {
super();
this.c1IsScrolling = false;
this.c2IsScrolling = false;
}
render() {
return (
<View style={{ flex: 1, marginTop: Constants.statusBarHeight }}>
<View style={{ flexDirection: 'row' }}>
<ScrollViewVerticallySynced
style={{ width: 50, marginTop: 60 }}
refe= {ref => (this.c2View = ref)}
name="C1"
color="#F2AFAD"
onScroll={e => {
if (!this.c1IsScrolling) {
this.c2IsScrolling = true;
var scrollY = e.nativeEvent.contentOffset.y;
this.c1View.scrollTo({ y: scrollY });
}
this.c1IsScrolling = false;
}}
/>
<ScrollView horizontal bounces={false}>
<View style={{ width: 400 }}>
<View style={{ height: 60, justifyContent: 'center', backgroundColor: '#B8D2EC' }}>
<Text>
I am Column Header!! I am Column Header!! I am Column Header!! I am Column
Header!! I am Column Header!! I am Column Header!! I am Column Header!!
</Text>
</View>
<ScrollViewVerticallySynced
style={{ width: 400 }}
refe= {ref => (this.c1View = ref)}
name="C2"
color="#D9E4AA"
onScroll= {e => {
if (!this.c2IsScrolling) {
this.c1IsScrolling = true;
var scrollY = e.nativeEvent.contentOffset.y;
this.c2View.scrollTo({ y: scrollY });
}
this.c2IsScrolling = false;
}}
/>
</View>
</ScrollView>
</View>
</View>
);
}
}
class ScrollViewVerticallySynced extends React.Component {
render() {
const { name, color, style, onScroll, refe } = this.props;
return (
<ScrollView
key={name}
ref={refe}
style={style}
scrollEventThrottle={1}
onScroll={onScroll}
bounces={false}
showsVerticalScrollIndicator={false}
>
{someRows(name, 25, color)}
</ScrollView>
);
}
}
const someRows = (name, rowCount, color) =>
Array.from(Array(rowCount).keys()).map(index =>
(<View
key={`${name}-${index}`}
style={{
height: 50,
backgroundColor: index % 2 === 0 ? color : 'white',
flex: 1,
alignItems: 'center',
justifyContent: 'center',
}}
>
<Text>
{name} R{index + 1}
</Text>
</View>),
);
You can find another example here
Related
Good Day Every one! i just want to ask for your opinion why does my code display the error at the title. I've been working on it for 2 days but haven't resolve it yet. I hope somebody will help me. Thank you! Here is my actual Code. I'm using cloudinary where i save the image (which works perfectly) and firestore as my database. the error occurs when I apply Insert function on firestore for database.
import React, { useState, Component } from 'react'
import {
StyleSheet,
View,
Text,
Dimensions,
TouchableOpacity,
Image,
TextInput,
Platform,
ActivityIndicator, ScrollView, KeyboardAvoidingView, Picker
} from 'react-native';
import ImagePicker from 'react-native-image-picker';
import firebase from './firebase';
const App = (props) => {
const [photo, setPhoto] = useState('https://res.cloudinary.com/{my_Cloud_name}/image/upload/v1585540130/bg_3__1580384977_49.145.192.210_rnmved.jpg');
const selectPhotoTapped = () => {
const options = {
title: 'Select Photo',
storageOptions: {
skipBackup: true,
path: 'images',
},
};
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else {
const source = {
uri: response.uri,
type: response.type,
name: response.fileName,
}
cloudinaryUpload(source)
console.log('Source: ', source);
console.log('cloudinary upload: ', photo);
return (photo);
}
});
}
const cloudinaryUpload = (photo) => {
const data = new FormData()
data.append('file', photo)
data.append('upload_preset', '{my_upload_present}/')
data.append("cloud_name", "{my_Cloud_name}/")
fetch("https://api.cloudinary.com/v1_1/{my_Cloud_name}//upload", {
method: "post",
body: data
}).then(res => res.json()).
then(data => {
setPhoto(data.secure_url)
}).catch(err => {
Alert.alert("An Error Occured While Uploading")
})
}
class AddPost extends Component {
state = {
image: '',
section: '',
unit: '',
price: '',
product: '',
status: '',
hasError: false,
errorText: '',
isLoading: false,
}
onChangeTitle = title => {
this.setState({ image })
this.setState({ section })
this.setState({ unit })
this.setState({ price })
this.setState({ product })
this.setState({ status })
}
onSubmit = async () => {
try {
const newDocumentData = this.ref.collection('products').doc().id;
this.setState({
loading: true,
});
const userId = firebase.auth().currentUser.uid;
this.ref.collection('products').doc(newDocumentData).set({
store_id: firebase.auth().currentUser.uid,
pr_name: this.state.product,
pr_id: newDocumentData,
pr_price: this.state.price,
pr_unit: this.state.unit,
pr_store_name: firebase.auth().currentUser.email, //change into name of store.
pr_section : this.state.section,
pr_image: this .state.image,
prod_status: 'active',
}).then((docRef) => {
this.setState({
image: '',
section: '',
unit: '',
price: '',
product: '',
status: '',
isloading: false,
});
Actions.gold();
})
} catch (e) {
console.error(e)
}
}
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View>
<View style={styles.imageContainer}>
<Text style={{fontSize: 20, textAlign: 'center', marginBottom: 7}}> Add Product </Text>
<ScrollView
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}>
<KeyboardAvoidingView enabled >
<Image source={{ uri: photo }} style={{
width: 200,
height: 200,
borderRadius: 100,
alignSelf: 'center',
}}/>
<TextInput
label="Enter Product"
placeholder="Enter Product"
label="Enter Product"
value={this.state.product}
onChangeText={product => this.onChangeTitle(product)}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<TextInput
placeholder="Enter Price"
keyboardType={'decimal-pad'}
value={this.state.price}
onChangeText={price => this.onChangeTitle(price)}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<Picker
style={{height: 50, width: 300}}
onValueChange={(TextInputValue, itemIndex) =>
this.setState({unit: TextInputValue})}>
<Picker.Item label = "Select Unit" />
<Picker.Item label = "Kilo" value = "Kilo" />
<Picker.Item label = "Each" value = "Each" />
<Picker.Item label = "Bottle" value = "Bottle" />
<Picker.Item label = "Pack" value = "Pack" />
<Picker.Item label = "Sack" value = "Sack" />
</Picker>
<Picker
style={{height: 50, width: 300}}
onValueChange={(TextInputValue, itemIndex) =>
this.setState({section: TextInputValue})}>
<Picker.Item label = "Select Section" />
<Picker.Item label = "Meat" value = "Meat" />
<Picker.Item label = "Vegetable" value = "Vegetable" />
<Picker.Item label = "Fruits" value = "Fruits" />
<Picker.Item label = "Biscuits" value = "Biscuits" />
<Picker.Item label = "Condiments" value = "Condiments" />
<Picker.Item label = "Canned Goods" value = "Canned Goods" />
<Picker.Item label = "Drinks" value = "Drinks" />
<Picker.Item label = "Diapers/Napkin" value = "Diapers/Napkin" />
<Picker.Item label = "Frozen Products" value = "Frozen Products" />
<Picker.Item label = "Junk Foods" value = "Junk Foods" />
<Picker.Item label = "Milk" value = "Milk" />
<Picker.Item label = "Soap/Shampoo" value = "Soap/Shampoo" />
<Picker.Item label = "Pesonal Items" value = "Pesonal Items" />
<Picker.Item label = "Pasta/Noodleslete" value = "Pasta/Noodles" />
</Picker>
<TextInput
placeholder="Enter Description"
multiline={true}
numberOfLines={4}
label="Enter Product"
value={this.state.Description}
onChangeText={Description => this.onChangeTitle(Description)}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<TextInput
placeholder="Enter image"
value={ photo }
onChangeText={image => this.onChangeTitle(image)}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<TouchableOpacity onPress={selectPhotoTapped} style={styles.uploadButton}>
<Text style={styles.uploadButtonText}>Upload</Text>
</TouchableOpacity>
<TouchableOpacity activeOpacity = { .4 } style={styles.uploadButton} >
<Text style={styles.TextStyle}> INSERT PRODUCT TO SERVER </Text>
</TouchableOpacity>
<TouchableOpacity activeOpacity = { .4 } style={styles.uploadButton} >
<Text style={styles.TextStyle}> SHOW ALL INSERTED PRODUCTS RECORDS</Text>
</TouchableOpacity>
<TouchableOpacity activeOpacity = { .4 } >
<Text style={styles.TextStyle}> </Text>
</TouchableOpacity>
</KeyboardAvoidingView>
</ScrollView>
</View>
</View >
);
};
}
}
export default App;
const styles = StyleSheet.create({
imageContainer: {
height: Dimensions.get('window').height
},
backgroundImage: {
flex: 1,
resizeMode: 'cover',
},
uploadContainer: {
backgroundColor: 'white',
borderTopLeftRadius: 45,
borderTopRightRadius: 45,
position: 'absolute',
bottom: 0,
width: Dimensions.get('window').width,
height: 200,
},
uploadContainerTitle: {
alignSelf: 'center',
fontSize: 25,
margin: 20,
fontFamily: 'Roboto'
},
uploadButton: {
borderRadius: 16,
alignSelf: 'center',
shadowColor: "#000",
shadowOffset: {
width: 7,
height: 5,
},
shadowOpacity: 1.58,
shadowRadius: 9,
elevation: 4,
margin: 10,
padding: 10,
backgroundColor: '#fe5b29',
width: Dimensions.get('window').width - 60,
alignItems: 'center'
},
uploadButtonText: {
color: '#f6f5f8',
fontSize: 20,
fontFamily: 'Roboto'
},
MainContainer :{
alignItems: 'center',
flex:1,
paddingTop: 30,
},
MainContainer_For_Show_StudentList_Activity :{
flex:1,
paddingTop: (Platform.OS == 'ios') ? 20 : 0,
marginLeft: 5,
marginRight: 5
},
TextInputStyleClass: {
textAlign: 'center',
width: '90%',
marginBottom: 7,
height: 40,
borderWidth: 1,
borderColor: '#FF5722',
borderRadius: 5 ,
},
TouchableOpacityStyle: {
paddingTop:10,
paddingBottom:10,
borderRadius:5,
marginBottom:7,
width: '90%',
backgroundColor: '#00BCD4'
},
TextStyle:{
color:'#fff',
textAlign:'center',
},
rowViewContainer: {
fontSize: 20,
paddingRight: 10,
paddingTop: 10,
paddingBottom: 10,
},
});
The return should have your JSX code in it to return Something.
Your current return has JSX code but it is all under your AddPost class while your App function has nothing to return.
You are using useState which is used for functional components and setState which is used for class components combined. I suggest you should use only one type of component at a time in a project to make your code simpler and better.
To make this work I suggest you should add your AddPost class under App's return.
eg
const App = (props) => {
//somewhere here
return(
//only if this is your initial file
//else import other file and write followingly
<AddPost/>
)
export default App;
I am trying my react native app on android and iOS using the release mode. unfortunately, there is an animation that doesn't trigger in release mode which works perfectly on debug mode.
i have tried to use the 'useNativeDriver: true' which improved the animation on android but didn't fix the issue
for ref:
"react-native": "0.56.0"
my Drawer.js
toggle = () => {
Animated.timing(this.x_translate, {
toValue: this.state.drawerOpen ? 0 : 1,
duration: this.state.animationDuration,
useNativeDriver: true
}).start();
this.setState({ drawerOpen: !this.state.drawerOpen })
}
render() {
const menu_moveX = this.x_translate.interpolate({
inputRange: [0, 1],
outputRange: [-this.state.width, 0]
});
return (
<Animated.View style={[this.props.style, styles.drawer, {
transform: [
{
translateX: menu_moveX
}
]
}]}>
<ImageBackground
source={require('../images/background.png')}
style={{ width: '100%', height: '100%', alignItems: 'center' }}
>
<View style={styles.blank}></View>
<AutoHeightImage source={require('../images/image.png')} width={0.7 * this.state.width} />
<LineDashboard navigate={this.props.navigate} items={[this.menu[0], this.menu[1]]} sizeIcon={30} />
<LineDashboard navigate={this.props.navigate} items={[this.menu[2], this.menu[3]]} sizeIcon={30} />
<LineDashboard navigate={this.props.navigate} items={[this.menu[4], this.menu[5]]} sizeIcon={30} />
</ImageBackground>
</Animated.View>
)
}
my dashboard.js
componentDidMount() {
this.props.navigation.setParams({
handleThis: () => {
console.log(this.drawer);
this.setState({ loaded: true })
this.drawer.toggle();
}
});
}
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
return {
headerTitle: 'Home Page',
headerLeft: (
<TouchableOpacity
onPress={() => {
params.handleThis();
}}
style={{ marginLeft: 20 }}
>
<Icon name="menu" size={25} color="black" />
</TouchableOpacity>
),
headerRight: (
<TouchableOpacity
onPress={() => {
console.log(navigation);
// navigation.goBack(null)
navigation.navigate('Login');
}}
style={{ marginRight: 20 }}
>
<Text style={{ color: 'red' }}>Log Out</Text>
</TouchableOpacity>
)
}
}
render() {
const { navigate } = this.props.navigation;
return (
<View style={styles.page}>
<ScrollView>
<View style={styles.pageContainer}>
<View style={{ height: 30 }} />
<AutoHeightImage source={require('../images/patient_primary_logo_white.png')} width={0.7 * width} />
<View style={styles.separator} />
<DashboardNotificationTile title={'Your Notifications'} onPress={() => navigate('Notifications')}>
<Text>You have 2 new notifications</Text>
<Text>Please click to see more</Text>
</DashboardNotificationTile>
<DashboardTile title={'Your Visits'}>
<Text>You have 1 upcoming visit</Text>
<SimpleButton onPress={() => navigate('ToBook')} title='View All Visits' width={'100%'} style={{ marginTop: 16 }} color={'green'}/>
</DashboardTile>
<DashboardTile title={'Your Expense Claims'}>
<Text>You have 2 open expense claims</Text>
<SimpleButton onPress={() => navigate('Open')} title='View All Expense Claims' width={'100%'} style={{ marginTop: 16 }} />
</DashboardTile>
</View>
</ScrollView>
<DrawerDashboard navigate={navigate} onRef={(ref) => this.drawer = ref} style={this.state.loaded ? { opacity: 1 } : { opacity: 0 }} />
</View >
)
}
in Dashboard.js, i have a headerLeft that should trigger the function handleThis() which doesn't seems to be doing. however, when pressed, the TouchableOpacity component stay 'selected' rather than coming back to its original state.
any suggestion?
thanks
EDIT:
the issue occurs at any time when the debugger is not on. sorry i just discovered it right now. The animation works perfectly if the remote JS debugger is launched.
So, i thought the issue may be the processing time, as the app is working slower when the debugger is on, maybe my handleThis() function was not loaded...
So, I moved the setParams() from the ComponentDidMount to WillMount.
didn't worked :\
Any suggestion?
I just want to fit an image of any size to the phone screen, so it just stays there as a background. I have the same issue with a logo I'm trying to put in the footer, I can't get it to fit in the it's view container.
I've tried many solutions I found in similar questions, using resizeMode and many width/height values, but nothing seems to work. My image is always displayed the same way.
Code for the image component:
import React from 'react';
import { View, Image } from 'react-native';
const Workspace = (props) => {
return (
<View
style = {styles.workspaceStyle}>
<Image
source={props.img}
resizeMode = 'contain'/>
{props.children}
</View>
);
};
const styles = {
workspaceStyle: {
flex: 1
}
}
export default Workspace;
My app.js render and style code:
render() {
return (
<View style = {{flex: 1}}>
<Workspace
img={require('./images/quarto.png')}/>
<ScrollView>
<Header>
<HeaderItem img={require('./images/camera.png')}/>
<HeaderItem img={require('./images/camera.png')}/>
<HeaderItem img={require('./images/camera.png')}/>
<HeaderItem img={require('./images/camera.png')}/>
</Header>
</ScrollView>
<ScrollView style = {{flexDirection: 'row'}}>
{this.sideMenuShow()}
</ScrollView>
<Footer>
<View style = {styles.logoContainerStyle}>
<Image
style = {styles.logoStyle}
source = {require('./images/magicalStage.png')}
resizeMethod = "scale"
/>
</View>
<Text style = {{color: 'white', marginTop: 5, marginBottom: 2}}>teste, teste, teste, teste</Text>
</Footer>
</View>
);
}
}
const styles = {
logoContainerStyle: {
marginRight: 5,
marginLeft: 5,
marginTop: 2,
marginBottom: 3,
width: "20%"
},
logoStyle: {
paddingLeft: 2,
paddingRight: 2
}
}
Thanks in advance!
EDIT:
In app.js, your outer view need to use width and height of the screen:
width: Dimensions.get('window').width,
height: Dimensions.get('window').height
Next, in Workspace: use stretch instead of contain ( same for your footer, add resizeMode )
resizeMode: 'stretch',
I do mine like this:
BackgroundImageStyle.js
import { StyleSheet } from 'react-native'
export default StyleSheet.create({
container: {
flex: 1,
position: 'absolute',
top: 0,
left: 0,
bottom: 0,
right: 0
},
image: {
flex: 1,
resizeMode: 'cover',
}
})
BacgroundImage.js
import React, { Component } from 'react'
import { View, Image } from 'react-native'
import styles from './BackgroundImageStyle'
export default class BackgroundImage extends Component {
render() {
return (
<View style={styles.container} >
<Image
style={styles.image}
source={this.props.source}
/>
</View>
)
}
}
then you can use it like
<BackgroundImage source={your_image}/>
I hope everything is clear, the trick is to set position absolute and then top, left, bottom, and right to 0
You can use the ImageBackground component from react-native
https://facebook.github.io/react-native/docs/imagebackground
return (
<ImageBackground source={...} style={{width: '100%', height: '100%'}}>
<Text>Inside</Text>
</ImageBackground>
);
The value set in asyncstorage is null and also the log for usertext is { [TypeError: undefined is not an object (evaluating 'this.state.usertext')] line: 30, column: 34 }
what might be the problem here?
'use strict'
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Navigator,
Text,
TextInput,
Button,
AsyncStorage,
View
} from 'react-native';
import { Actions } from 'react-native-router-flux';
import api from './utilities/api';
export default class LoginScreen extends Component{
constructor(props) {
super(props);
this.state = { usertext: 'placeholder' , passwordtext: 'placeholder' ,buttonvalue: '
Login'};
}
async login() {
const res = await api.getLoginResult();
const status= res.status;
console.log('log'+status);
if(status==='success'){
try {
console.log('usertext'+this.state.usertext);
await AsyncStorage.setItem('username', this.state.usertext);
var username = await AsyncStorage.getItem('username');
console.log('username'+username);
await AsyncStorage.setItem('password', this.state.passwordtext);
} catch (error) {
// Error saving data
console.log(error);
}
Actions.HomeScreen();
}
}
render() {
return (
<View style={styles.container}>
<View style={styles.containerLogin}>
<View style={styles.headerContainer}>
<Text style={styles.welcome}>PLEASE LOGIN</Text>
</View>
<View style={styles.inputlayouts}>
<TextInput
onChangeText={(usertext) => this.setState({usertext})}
value={this.state.usertext}
/>
<TextInput
onChangeText={(passwordtext) => this.setState({passwordtext})}
value={this.state.passwordtext}
/>
</View>
<View style={styles.buttonView}>
<Button
style={styles.buttonstyle}
onPress={this.login}
title={this.state.buttonvalue}
color="#FF7323">
</Button>
</View>
</View>
</View>
)
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'stretch',
backgroundColor: '#1AB591',
},
headerContainer:{
backgroundColor:'#FF7323'
},
buttonView:{
marginLeft:15,
marginRight:15,
marginBottom:15
},
inputlayouts:{
marginLeft:6,
marginRight:6,
marginBottom:10,
},
containerLogin: {
justifyContent: 'center',
alignItems: 'stretch',
backgroundColor: '#FFF',
marginLeft:20,
marginRight:20
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
color:'#FFF'
},
buttonstyle: {
width:20,
}
});
Change
<Button
style={styles.buttonstyle}
onPress={this.login}
title={this.state.buttonvalue}
color="#FF7323">
</Button>
to
<Button
style={styles.buttonstyle}
onPress={this.login.bind(this)}
title={this.state.buttonvalue}
color="#FF7323">
</Button>
When you do onPress={this.login}, the method reference to this will be different than your component. Binding this to method, allows you to reference your this in the function.
On Android 4.4, ListView separator lines are inconsistent in thickness, and some do not render.
I can't see how this can be a code issue, this is how I render them:
separator: {
height: 1,
backgroundColor: 'grey',
}
...
<ListView
renderSeparator={(sectionID, rowID) =>
<View key={`${sectionID}-${rowID}`} style={styles.separator} />
}
.../>
Here is a screenshot of a View with this problem:
This issue does not happen on iOS or Android 6.
Anyone had this problem before?
Update
I did a test, this is not Android4 issue. It happens on all API version when running on Nexus One device (in android emulator)
I had this issue on iOS and worked around it by adding a hairline margin, like so:
<View
style={{
...styles,
borderWidth: StyleSheet.hairlineWidth,
margin: StyleSheet.hairlineWidth,
}}
>
{// ...row content}
</View>
Just give the height:hairlineWidth in style
I had the same issue and solved changing the view height from a number to StyleSheet.hairlineWidth as some folks said before. Trying to be more visual/specific:
Before:
renderItemSeparator() {
return (
<View style={{ height: .2, backgroundColor: 'rgba(0,0,0,0.3)' }} />
);
}
After:
renderItemSeparator() {
return (
<View style={{ height: StyleSheet.hairlineWidth, backgroundColor: 'rgba(0,0,0,0.3)' }} />
);
}
Actually there is no fix. It's RN "render-canvas-bug".
But I found hack solution.
<ListView
style={Style.listView}
dataSource={data}
renderRow={(data) => this._renderRow(data)}
/>`
Style.listView: {
backgroundColor: '#fff',
}, // or another backgroundColor you need
Then:
_renderRow(goods) {
return (
<View key={'goods_' + goods.id} style={Style.listView_item}>
<TouchableOpacity or View or ...
style={[Style.flex, Style.flexRow, Style.separatorRow, Style.u_paddingVerticalS, Style.u_middle]}
onPress={() => this._xyz(goods)}>
<View>
<AppFont>{goods.name}</AppFont>
</View>
</TouchableOpacity or View or ...>
</View>
);
}
Only important TouchableOpacity style is Style.separatorRow to render your separator. This style should be inside listView_item, where you can use another styles.
listView: {
backgroundColor: '#fff',
},
listView_item: {
paddingHorizontal: em(1.5),
},
flex: {
flex: 1,
},
flexRow: {
flexDirection: 'row',
},
separatorRow: {
marginBottom: 1,
borderBottomWidth: 1,
borderBottomColor: Colors.canvasColor,
},
You can use StyleSheet.hairlineWidth instead of 1 but it's not a must.
I reported it on GitHub
My workaround was to style the containing view and text like this:
const styles = StyleSheet.create({
rowViewContainer: {
flex: 1,
paddingRight: 15,
paddingTop: 13,
paddingBottom: 13,
borderBottomWidth: 0.5,
borderColor: '#c9c9c9',
flexDirection: 'row',
alignItems: 'center',
},
rowText: {
marginLeft: 15,
},
});
This is the ListView:
<ListView
dataSource={this.state.dataSource}
renderRow={(data) => <View style={styles.rowViewContainer}>
<Text style={styles.rowText}>
{data.bb_first_name}
</Text>
</View>}
/>
Looks nice:
This happens because you have empty rows in your data source. You can style your separators to see it
To avoid this just filter your data.
I faced the same issue when trying to render a Divider with a width of 0.5.
It rendered properly on devices with pixel ratio of 2 (e.g. iPhone SE 2nd gen.) but rendered random width on devices with pixel ratio of 3 (e.g. iPhone 12).
As suggested by other answers, using Stylesheet.hairlineWidth fixes the random width issue but the problem was that the width was thinner than 0.5 on devices with pixel ratio of 3.
So this fixed my problem:
import { PixelRatio, View } from 'react-native';
...
export const Divider = () => {
const width = PixelRatio.roundToNearestPixel(0.5);
...
return <View style={{ width }} ... />
}