0

Here's what I currently have.

class App extends React.Component {
    constructor(props) {
      super(props)
      
      this.textInput = React.createRef();
      this.state = {
        value: 'select all on click'
      }
    }
  
  handleClick = e => {
    e.preventDefault();
    this.setState({ value: this.textInput.current.select()})
  };

  render() {
    return (
      <div>
        <input type="text" ref={this.textInput}
          value={this.state.value}
          onClick={this.handleClick}/>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));

This works, but in my browser I keep getting this error in handleClick: Cannot read property 'current' of undefined. This is because I'm using some <Child> component in place of <input> in my local environment. I've tried renaming the ref to match the parent prop as suggested here https://stackoverflow.com/a/53241934/6312629, but that also didn't work.

Any suggestions as to how to resolve this would be greatly appreciated!

Thank you very much!

helloWorld
  • 135
  • 3
  • 13

2 Answers2

0

If you start with a new project, I suggest to try out functional components with hooks.

Try to set ref yourself:


ref={ ref => {

this.textInput = ref

}}

Tob
  • 627
  • 6
  • 9
0

For react children components, the ref just needs to be forwarded to the child and passed to the actual input because refs aren't treated as props (similar to how keys are treated differently). So you can use React.forwardRef to extract the ref and pass it on as a prop to the child. It might look something like this for you, but you may find a better-fit solution here: https://reactjs.org/docs/forwarding-refs.html#forwarding-refs-to-dom-components

// App.js
class App extends React.Component {
    ...

    render() {
        return (
           <Child
              ref={this.textInput}
              handleClick={this.handleClick}
              value={this.state.value}
           />
        );
    }
}

// Child.js
class Child extends React.Component {
    render() {
        return (
          <div>
            <input type="text" ref={this.props.forwardedRef}
              value={this.props.value}
              onClick={this.props.handleClick}/>
          </div>
        );
    }
}

export default React.forwardRef((props, ref) => (
    <Child forwardedRef={ref} {...props} />
));
marsheth
  • 822
  • 6
  • 9