Jose
Jose

Reputation: 441

React Native .focus() undefined

All works good in my code but when I try to .focus() I get an error:

null is not an object (evaluating 'ref_input.focus')

If a do console.log( ref_input ) returns an object correctly but I can't find Focus Function or reference.

const ScreenOne = () => {

     const ref_input = useRef( null );   

     render(){
      
          return (

              <CustomInput 
                    returnKeyType='next'
                    onSubmitEditing={ (event) => {
                        ref_input.current.focus()   // Not work
                        ref_input.focus() // Not work too
                    }}
                    ... bla bla more stuff
              />


              <CustomInput 
                    returnKeyType='done'
                    ref={ ref_input }
                    ... bla bla more stuff
              />

          )

     }

 }

.

import TextInput from 'react-native-paper';

class CustomInput extends React.Component {

    render(){
        
        return (

            <TextInput
                { ...this.props }
            />
        
        )
    
     }

 }
 

Upvotes: 1

Views: 1122

Answers (1)

Alessandro Carughi
Alessandro Carughi

Reputation: 1228

Try this:

const ScreenOne = () => {
    constructor(){
       super()
       this.ref_input = React.createRef()
       this.handleSubmit = this.handleSubmit.bind(this))
    }

    handleSubmit = () => {
       this.ref_input.current.focus()
    }

    render(){
  
      return (

          <CustomInput 
                returnKeyType='next'
                onSubmitEditing={ (event) => {
                     this.handleSubmit()
                }}
                ... bla bla more stuff
          />


          <CustomInput 
                returnKeyType='done'
                ref={ this.ref_input }
                ... bla bla more stuff
          />

      )

 }

}

Upvotes: 1

Related Questions