0

The code below makes an axios API call whenever the windows Tab is in focus. source Stackoverflow link

Now am working with a form input for chatText Messages. My question is

how do I make an API request when form Input is focused. I want to get a callback whenever my form input comes in focus.

Here is the Form inputs

 <input  type="text" name="chatText" onFocus={this.onFocus} />

Here is the code

import React, { Component, Fragment } from "react";
import { render } from "react-dom";
import axios from 'axios';



class Focus extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      chatText: ''
    };
this.onfocus = this.onfocus.bind(this);
  }

  componentDidMount() {
window.addEventListener("focus", this.onfocus());
  }

onfocus() {
alert('Am Focused');
 //Make axios call to get data from backend
}


  render() {
    return (
      <span>
        <label>
          <ul>

 <input  type="text" name="chatText" />

          </ul>
        </label>
      </span>
    );
  }
}
Nancy Moore
  • 2,322
  • 2
  • 21
  • 38

2 Answers2

0

Based on your code...

import React, { Component, Fragment } from "react";
import { render } from "react-dom";
import axios from 'axios';

class Focus extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      chatText: ''
    };
  }

 onfocus = ()=> {
 alert('Am Focused');
 //Make axios call to get data from backend
 }
  render() {
    return (
      <span>
        <label>
          <ul>
          <input  
            type="text" 
            name="chatText" 
            onFocus={this.onfocus} />
          </ul>
        </label>
      </span>
    );
  }
}
sathish kumar
  • 1,477
  • 1
  • 11
  • 18
0

The problem is in your code. As you made a typo in -

<input type="text" name="chatText" onFocus={this.onFocus} />

change onFocus to onfocus and it will fix your code.

swapnesh
  • 26,318
  • 22
  • 94
  • 126