ReactJS: The input is not triggering the onChange event

Take a look at this code snippet:

import React, { Component, useImperativeHandle } from 'react';

class SearchBar extends Component {
render() {
return <input onChange={this.onInputChange} />;
}

onInputChange(event) {
console.log(event)
}
}

export default SearchBar;

I'm not seeing any errors, but the console is not logging anything when I input text.

You can see a screenshot here of the input field and the console for reference.

Answer №1

To properly connect your event handler to your class component, the following steps need to be taken:

 import React, { Component, useImperativeHandle } from 'react';

 class SearchBar extends Component {
   constructor(props) {
     super(props);
     this.onInputChange = this.onInputChange.bind(this); //This step is essential
  }
   
  render() {
    return <input onChange={this.onInputChange} />;
  }
  
  onInputChange(event) {
    console.log(event)
  }
}

export default SearchBar;

Answer №2

Everything is functioning correctly on my end. I have emphasized the console.log outputs in the screenshot below: https://i.stack.imgur.com/abc123.png

If you want to view the text entered into the input tag, simply use console.log(event.target.value) instead of console.log(event)

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

Exploring Angular 4.0: How to Loop through Numerous Input Fields

I am looking to loop through several input fields that are defined in two different ways: <input placeholder="Name" name="name" value="x.y"> <input placeholder="Description" name="description" value"x.z"> <!-- And more fields --> or lik ...

React's setState function is overriding the current state

I am facing an issue with updating a single value in my state object. In a form, there is one input field for the name and I have implemented the following code in its onChange method: onChangeUpdateForm(e) { this.setState({ currentService ...

Is there a way to calculate the number of days between two selected dates using the bootstrap date range picker?

I recently implemented the bootstrap daterange picker for selecting start and end dates, and it's been working perfectly. However, I now have a requirement to display the count of days selected. Here's my current code: $('input[name="datera ...

How is it possible to access a variable in a function that hasn't been declared until later?

While working on a Dialog component, I had an unexpected realization. export const alert = (content: string) => { const buttons = [<button onClick={()=>closeModal()}>ok</button>] // seems alright // const buttons = [<button onCli ...

Struggling to retrieve information from a JSON file and display it within a component?

After accessing the JSON data and storing the necessary values in a dictionary named details, I am encountering an issue where the values are displayed when console logged from inside the function but appear as undefined when console logged in the parent f ...

Why is jQuery ajax not functioning in the view file in a node.js environment?

I have recently started working with Express Node.js and I am facing an issue with making an AJAX call or using jQuery from the HBS view. Below are my controller methods: router.get('/', function(req, res) { console.log("home get request"); ...

Setting the file type when uploading content: a step-by-step guide

When uploading a file to an S3 bucket, it's essential to identify the file extension and add the correct content type. $('#upload-files').on('click', function(e) { e.preventDefault(); var fileName = data.files[0].name; var ...

The equation:() is malfunctioning

Here is a code snippet I'm working with: $("#button").click(function () { for (var i = 0; i < 4; i++) { setTimeout(function () { $(".rows:eq("+i+")").css("background-color", "blue"); ...

Using TypeScript with React and Material-UI: Issue with undefined theme in createStyles()

Currently, I am delving into React with TypeScript and utilizing the Material UI framework for the frontend. In my quest to activate media queries, an error has crossed my path: Uncaught TypeError: Cannot read property 'up' of undefined ...

Is there a way for me to streamline the process of logging in using either Google or Facebook?

Is there a way for me to automate the scenario if I'm unable to locate the element using Appium Uiautomator? https://i.stack.imgur.com/Rjji4.png ...

Exploring a JSON Object with nested properties, crafting changes, and producing a fresh object: A step-by-step guide

I am attempting to manipulate a JSON object with nested properties by replacing numeric values with computed values and returning a new object. The original object looks like this: var obj = { "a0": { "count": 41, "name": "Park", "new": { ...

Setting headers in Node.js after they have already been sent to the client is not allowed

I'm currently enrolled in a node.js course on Udemy which seems to be outdated. I've encountered some errors that I'm struggling to resolve. Here's what I've tried so far: using next(); adding return res inside all if statements ...

What is the reason behind ASP MVC model binder's preference for JSON in POST requests?

Is there a way to bind data to a model when sending a 'GET' request with JSON.stringify() using AJAX? Currently, the model value is always null when using 'GET', but it works fine with 'POST'. Are there any solutions for this ...

Concealing overflow for text content through CSS styling

I am currently working with an element that contains both an image and text. View the Fiddle here Note: To see the full grid, resize the preview accordingly. The CSS I have written is as follows: .gridster .gs-w .item{ position: relative; wi ...

JavaScript - convert the values of an array within a JSON object into separate strings

I am receiving a JSON object from an API, and my next step involves some string analysis of each key value. This process works perfectly for 90% of the objects I receive because the key values are strings. { ID: '0012784', utm_source: 'webs ...

Calculate values dynamically when styling material-UI components

Utilizing the Material-UI style to define the class. Now, I aim to adjust the height based on the browser's width. Is there a way to dynamically calculate this within makeStyles() or implement a workaround? This snippet below represents what I am t ...

The inner HTML functionality in Angular 2 seems to be malfunctioning when dealing with HTML tags

I am facing an issue with an array that includes displayName with HTML tags: this.topicsList = [ {id: "173", name: "Discussion1", displayName: "Discussion1", status: 1}, {id: "174", name: "discussion123", displayName: "discussion123", status: 1}, {id: "19 ...

An error occurred when attempting to run the command npm run compile:sass, displaying the message: npm ERR! missing script:

Everything seems to be in place with the sass folders and files, so what could be the issue? I have my package.json file set up correctly with the following code: { "name": "starter", "version": "1.0.0", " ...

Turn off javascript on a website that you are embedding into another site

Is it feasible to deactivate JavaScript on a website you are attempting to embed? If the website is working against your embedding efforts, could you effectively neutralize all their JavaScript, even if it requires users to engage with the site without J ...

What is the best method to add data to a child array located within a nested array?

Struggling to create an array that will display data in the following format: Healthcare -- Insights driven by data for improved healthcare -- Urban Analytics Transport -- Urban Analytics Cities -- Urban Analytics I have attempted ...