I work actually on a picker component which needs to be at center on the middle value by default. I have created a modal with a ScrollView with ref and use the scrollTo function view on this exemple: https://snack.expo.io/SkileGr9X
Tried all but got this error :
Cannot read property 'scrollTo' of undefined
Does someone have any tip?
import React from 'react';
import { Modal,TouchableHighlight,View, StyleSheet,ScrollView,TextInput} from 'react-native';
import { Container, Header, Content, Icon,Picker, Form, Text,Left, Body, Right, Title,Button,List, ListItem} from "native-base";
const Mystyles = StyleSheet.create({
container:{
},
btnSelect:{
borderColor:'#a1a1a1',
borderWidth:1,
padding:5,
margin:10,
height:33
},
placeholderSelect:{
color:'#a1a1a1',
},
valueSelect:{
color:'black',
}
});
let scrollYPos = 0;
var itemsArray = [];
for(let i=0; i < 90;i++){
itemsArray.push(i);
}
export default class Selects extends React.Component {
constructor(props){
super(props);
this.state = {
items:itemsArray,
modalVisible: false,
isLoading:false,
selectValue:'',
placeholder:'placeholder',
type:'int'
}
}
setModalVisible(visible) {
this.setState({modalVisible: visible});
scrollYPos = this.state.screenHeight * 1;
this.scroller.scrollTo({x: 0, y: scrollYPos});
}
selectItem = (item) =>{
this.setState({
selectValue:item,
modalVisible:false
});
this.props.returnSelect(item);
}
render(){
const { selectValue,items,placeholder } = this.state;
return (
<View style={Mystyles.container}>
<Modal
animationType="slide"
presentationStyle='formSheet'
visible={this.state.modalVisible}>
<Header>
<Left>
<Button transparent onPress={() => {this.setModalVisible(false);}}>
<Icon name='arrow-back' />
</Button>
</Left>
<Body>
<Title>Header</Title>
</Body>
<Right />
</Header>
<ScrollView ref={(scroller) => {this.scroller = scroller}}>
<List dataArray={items}
renderRow={(item) =>
<ListItem onPress={() => {this.selectItem(item);}} selected={selectValue == item}>
<Left>
<Text>{item}</Text>
</Left>
<Right>
<Icon name="arrow-forward" />
</Right>
</ListItem>
}>
</List>
</ScrollView>
</Modal>
<TouchableHighlight
style={Mystyles.btnSelect}
underlayColor="rgba(0, 0, 0, 0.1)"
onPress={() => {
this.setModalVisible(true);
}}>
<Text style={selectValue ? Mystyles.valueSelect : Mystyles.placeholderSelect}>{selectValue ? selectValue : placeholder}</Text>
</TouchableHighlight>
</View>
);
}
}
<Button transparent onPress={() => {this.setModalVisible(false);}}>
When you press this button, Modal gone so you can scroll when view gone. You have to check:
if(this.state.modalVisible){
scrollYPos = this.state.screenHeight * 1;
this.scroller.scrollTo({x: 0, y: scrollYPos});
}
BTW screenHeight is a const, don't use state.