The React onChange event fails to trigger

Why isn't the onChange event firing in the input tag? I used LinkedStateMixin to track the input value before, but now I want to add an onChange event to run a function. After removing LinkedStateMixin, the onChange event still doesn't fire. I even tried adding e.stopPropagation() to setUsername(), but that didn't work either. Other events like onKeyDown and onClick also did not fire. What could be causing this issue?

var React = require('react');

var SessionActions = require('../../actions/session_actions');
var UserStore = require('../../stores/user_store');

var LogInForm = React.createClass({

  getInitialState: function() {
    return ({
      user: undefined,
      username: '',
      password: '',
    });
  },

  componentDidMount: function() {
    this.token = UserStore.addListener(this.updateUserStore);
  },

  componentWillUnmount: function() {
    this.token.remove();
  },

  updateUserStore: function() {
    this.setState({user: UserStore.all()});
    this.setState({username: ''});
    this.setState({password: ''});
  },

  setUsername: function(e) {
    console.log("Fired");
  },

  handleSubmit: function(e) {
    e.preventDefault();
    SessionActions.logIn({
      username: this.state.username,
      password: this.state.password
    });
    this.updateUserStore();
  },

  render: function() {
    return (
      <div>
        <h4>Log In</h4>
        <div> </div>
        <form onSubmit={this.handleSubmit}>
          <input onChange={this.setUsername} placeholder="Username" type="text"/>

          <input placeholder="Password" type="password"/>

          <input type="submit" value="Log In"/>
        </form>
      </div>

    );
  }
});

module.exports = LogInForm;

Answer №1

After examining the code you shared, I went ahead and created a jsfiddle to test it out. Surprisingly, the onchange event still triggers despite the warnings present. It seems like there might be another issue with your code.

Are you able to see if the component renders at all? If possible, could you share a fiddle where the functionality is not working so that I can investigate further?

Answer №2

Update the function name from setUsername to handleUsername.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Don't initialize each variable within the constructor of a class, find a more efficient approach

I have a collection of JavaScript classes representing different models for my database. Each model contains attributes such as name, email, and password. Is there a more efficient way to create a new User instance without manually assigning values to ea ...

Using a comma format while typing in Angular ensures that the input field

When using jqxwidget from here, the default format includes commas separated by underscores. I am looking to have the field empty initially, with commas appearing as the user types - similar to a F2 cell renderer. For example, typing 100 should display a ...

What is the best way to eliminate an object from an array of objects depending on a certain condition?

I have an array of objects structured like so: data = [ { "name":"abc", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa9b9899ba9d979b9396d4999597">[email protected]&l ...

Optimizing the management of optional post fields in an Express.js application

When creating an endpoint with Express that includes both mandatory and non-mandatory fields in the post request, what is the optimal strategy for handling this? Would it be best to use something like if (field exists in req.body) { set variable } else { ...

What could be causing my images not to show up when I use string interpolation for src links in Vue.js?

I've encountered an issue while working on Vue.js where I'm struggling to render a couple of images from the local directory. What puzzles me is that this problem arises when using string interpolation, like in the code snippet below: <img :s ...

Validation of a string or number that is not performing as expected

I have been working with the yup library for JavaScript data validation, but I am encountering unexpected behavior. Despite thoroughly reviewing their documentation, I cannot pinpoint where I am misusing their API. When I run the unit test below, it fails ...

Tips for extracting HTML tags directly from JSON data

In my dataset, I have a JSON illustration [{ "Field1": "<header class=\"main-header dark-bg\">\n\t\t<div class=\"row\">\n\t\t\t\t<div class=\"col-xl-3\">\n< ...

What is the best way to convert minutes into both hours and seconds using javascript?

In order to achieve this functionality, I am trying to implement a pop-up text box where the user can choose either h for hours or s for seconds. Once they make their selection, another pop-up will display the answer. However, I am facing issues with gett ...

Step-by-step guide on dynamically adding "Input Tags" to the DOM at runtime using Selenium's JavascriptExecutor

In order to dynamically add the following element to the DOM during run time, I need assistance... <input type="text" name="imagesToAdd" value="3566"> My initial attempt was to use Selenium JavascriptExecutor for this task. However, I encounter ...

Transitioning to TypeScript: Why won't my function get identified?

I am in the process of transitioning a functional JavaScript project to TypeScript. The project incorporates nightwatch.js Below is my primary test class: declare function require(path: string): any; import * as dotenv from "dotenv"; import signinPage = ...

Are there any resources available to ensure my jQuery script is compatible with multiple browsers?

After realizing that Internet Explorer does not support certain selectors in jQuery, I began to question how to ensure my code will function properly during the writing process. As a Linux user, my testing options are limited to Chrome and Firefox. Is ther ...

How can one generate an array containing all attributes found in the HTML of a website?

I have a project idea where I want to be able to input a hyperlink address and then get a list of attribute contents as the output. For instance, if I input a Netflix genre hyperlink for Adventure Movies, I'd like to receive a list with all the movie ...

Every time I attempt to log in, the code keeps generating an error message net::ERR_EMPTY_RESPONSE. If successful, it should redirect to the

The code is producing a net::ERR_EMPTY_RESPONSE error when attempting to log in. The username and password are hardcoded. I simply want the admin to input their credentials on the Employee.html page, and if they match the ones in the main.js file, redirec ...

How can I transmit information to the model without relying on query string parameters in Express?

Currently, I am working with two controllers - authController and onboardingController. The authController communicates with the onboardingController using the following line of code: res.redirect('/onboarding/info?profileId=' + profile.id + &ap ...

Unlimited digest loop in Angular.js caused by nested ng-repeat and filter

In my AngularJS project, I have developed a custom filter that categorizes elements by type and performs a search for multiple search terms across all attributes of devices. angular.module('abc').filter('searchFor', function(){ return ...

Endless cycle of React hooks

I am struggling to understand why I keep encountering an infinite loop in my useClick function. I can see that I am updating the state value inside the useEffect using setVal, but according to the second parameter, useEffect should only run on onClick as ...

What is the best method for eliminating buttons and text in a row using CSS?

I faced an issue when trying to create a row, so I improvised with the following setup. However, I actually need a proper row layout for both the Google button and telephone number button. Here are my CSS snippets: .google-button { color: white; borde ...

Is there a Google Maps feature that displays clusters in a dropdown

Currently, I am utilizing Google Maps to place pins all over the world and implementing markercluster.js to cluster those pins when they are nearby. One feature I am trying to incorporate is the ability to hover over a cluster of pins and have a dropdown d ...

Open a JavaScript file to retrieve data from a nearby JSON object

I've been trying to access a local JSON file using a JavaScript file, but for some reason it's not working. Even though I'm sure the URL is correct, the code keeps failing to retrieve data from the JSON object. JavaScript file: var pieData ...

Generate a link that can easily be shared after the content has loaded using

One feature on my website involves a content container that displays different information based on which list item is clicked (such as news, videos, blogs, etc.). This functionality is achieved by using jQuery's load method to bring in html snippets ...