13 February 2020

Set focus on input after render in react js

  • Create Components folder under src folder
  • Add SetFocusOnInputAfterRender.js file under Components folder and add below Code
import React, { Component } from "react";

class SetFocusOnInputAfterRender extends Component {
  constructor() {
    super();
    this.emailInput = React.createRef();
  }
  componentDidMount() {
    this.emailInput.current.focus();
  }
  render() {
    return (
      <>
        <label>Name</label>
        <input type="text" placeholder="Enter name" ref={this.nameInput} />
        <br />
        <label>Email</label>
        <input type="email" placeholder="Enter email" ref={this.emailInput} />
      </>
    );
  }
}

export default SetFocusOnInputAfterRender;
  • Open App.js file and update code as below
import React from 'react';
import SetFocusOnInputAfterRender from './Components/SetFocusOnInputAfterRender'

function App() {
  return (
    <div>
      <SetFocusOnInputAfterRender/>
    </div>
  );
}

export default App;

Output:


No comments:

Post a Comment