Search code examples
reactjsref

how to get ref's in reusable component in react js


Hi guys I am new bee to react js . I have reusable component which has ref property .When I pass _ref props value to Reusablecomponent . I don't get proper ref value. I mocked the same in below code (What value i have received in Reusable component).

Reusable component

     class A extends React.Component {
        constructor(props){
        super(props)
        ...
        }
    componentDidMount() {
//TypeError: Cannot read property 'focus' of undefined
        if (this.props._ref && !this.props._ref.disabled) {
            this.props._ref.current.focus();
            this.props._ref.current.select();
        }
     }
        render(){

        //If I console.log of this.props._ref . 
        //I got function like function (input) { return this2.firstField  = input  }
        //If i try to do any focus () or select() method I got an error with msg 
        // Focus or select method is not a function 

        return(
        <div>
        <input  type="text" ref={this.props._ref} value = {this.props.value}  />
        </div>
        )
        }

Own component

class own extends React {
constructor(props){
super(props);
}

handleChange = () => {
//I need to check the cursor . where its reside if the cursor in first input field I need to disable the button like I have requirement . 
}

render(){

return(
<A value = {"userName"} _ref = {input => this.firstField = input }/>
)

}
}

As I mentioned my scenario , I dont have any clue how to do this . Am i expected in handleChange method is possible ? . Please guide me .


Solution

  • As stated in the ReactJs Docs:

    When a ref is passed to an element in render, a reference to the node becomes accessible at the current attribute of the ref.

    Try using this.props._ref.current.focus()