[Solved] Focus issues with react


You are not using createRef and trying to use focus method which is the issue.
Simply create callback ref and you are good to go.

Here is the working code below and codesandbox link.

index.js

import React from "react";
import ReactDOM from "react-dom";
import FocusComp from "./FocusComp";

class App extends React.Component {
  state = {
    focus: false
  };
  render() {
    return (
      <div className="App">
        <button onClick={() => this.setState({ focus: true })}>
          click me to focus
        </button>
        <br />
        <br />
        <FocusComp isFocussed={this.state.focus} />
      </div>
    );
  }
}

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

FocusComp.js

import React from "react";

class FocusComp extends React.Component {
  componentWillReceiveProps(nextProps) {
    if (nextProps.isFocussed) {
      this.myRef.focus();
    }
  }
  render() {
    return <input ref={myRef => (this.myRef = myRef)} />;
  }
}

export default FocusComp;

I created a working code to make you understand what you did wrong.

Things to improve:-

1) use createRef instead of callback.

2) Don’t use componentWillReceiveProps as it’s deprecated.

Hope that helps!!!

1

solved Focus issues with react