Search code examples
reactjssecurityinputrefsetfocus

React setFocus on Input field - security?


Question: In React I read that you should not use 'ref' and 'findDOMNode' for security reasons. (insecurely accessing native DOM Elements...)

Is there another way to set the focus manually in input fields?


Solution

  • You can try the following:

        function manualFocus() {
        document.getElementById("text").focus();
      }
    
      return (
        <div className="App">
          <input type="text" id="text" name="text"></input>
          <input type="text2" id="text2" name="text2"></input>
          <button type="button" onClick={() => manualFocus()}>Manual Focus</button>
        </div>
      );