-1

I am trying to focus on error fields inside of a form and I am using ref to do that but somehow ref always returns null and I am getting errors, I want to use/pass this ref to focus on error field , here error is stored in state which i have not included in code

here is the basic code,

class Form extends Component {
    constructor(props) {
        super(props);

        this.textInput = React.createRef();
        this.getErrors = this.getErrors.bind(this);
    }

    componentWillUnmount() {
        /////
    }

renderSubmitAction() { 

if(errors) {
            
            this.textInput.current.focus();
            
        }

}


render() {
return (
<View key={propertyName}>
                        <FormInput
                            id={id_prefix + propertyName}
                            key={propertyName}
                            ref={this.textInput}
                        />
                    </View>


)

const submitButton = this.renderSubmitAction();

        return (
            <View key={this.state.submitId} style={props.style}>
                {children}
                {props.children}
                {submitButton}
            </View>
        );

}


Curious_guy
  • 161
  • 11

1 Answers1

0

Problem

You are running this:

this.textInput.current.focus();

before this happens:

<FormInput
  id={id_prefix + propertyName}
  key={propertyName}
  ref={this.textInput}
/>

Solution

I'm not sure what this is supposed to do:

const submitButton = this.renderSubmitAction();

But you probably wanted to use this:

const submitButton = this.renderSubmitAction;
Konrad
  • 21,590
  • 4
  • 28
  • 64