2

I have created a scrollview which renders dynamic form elements. I could create "ref" for each of these dynamic children of the scrollview. But the problem I am facing is that I want to scroll to the exact child where there is a validation error in the form. But I cannot find the actual position of each child relative to the scrollview, so that I can scroll to that element.

I have tried adding the onLayout method to the child component, but it returns the position only once when its loaded and then the value remains same, even after scrolling.

My scrollview

<ScrollView style={{marginBottom: 55}} ref={(ref) => { this.formScrollList = ref; }}>
  {this.state.formElements.map((element, i) => {
    return (
      <TextboxInput quesNo={element.key + 1} required={element.required} error={this.state.errors[element.question_id]} quesType={element.type} quesId={element.question_id} placeholder={element.placeholder} onChangeHandler={this.onChangeHandler} label={element.label} defaultValue={this.state.answers[element.question_id]} showRequired={this.showRequired} index={element.index}/>
    )
  })}
</ScrollView>

My TextboxInput child

const TextboxInput = (props) => (
    <View style={styles.inputContainer} ref={setRef}>
        <Text style={styles.text}>{props.label || "Textbox"}{props.showRequired(props.required)}</Text>
        <TextInput style={[styles.textInput, props.error === "empty" ? {borderWidth: 1, borderColor: "red"} : null]} {...props} onChangeText={props.onChangeHandler.bind(this, props.quesId, props.quesType, props.index)} placeholder={props.placeholder} underlineColorAndroid="transparent" defaultValue={props.defaultValue}/>
    </View>
)

I want to scroll to the exact child where there is a validation error in the form.

  • There is library available for this purpose . May be it works for you . Try this [react-native-scroll-into-view](https://github.com/slorber/react-native-scroll-into-view) . Possible duplicate [question](https://stackoverflow.com/questions/54928858/react-native-scrollview-how-to-scroll-to-a-child-component-from-another-child) – Mehran Khan Sep 06 '19 at 03:29
  • Thanks for letting me know about the library, it helped fix my problem. And this is similar to the question you have mentioned, but I had tried all the methods available in that solution none of them worked. – Subham Chatterjee Sep 09 '19 at 13:27

1 Answers1

-1

use scrollTo method of scrollview component.

Nahid Hasan
  • 687
  • 1
  • 10
  • 34