Getting an input value dynamically in a React variable when there is a change in the input field

I am having an issue with my search text box. I need to extract the value onchange and send a request to an API, but when I try using the normal event.target method, it shows an error. How can I fix this? The problem is that onchange, I need to call a function with some arguments, so I cannot take the easy route.

Here is the code for my text box:

<input className="ReactSearchBox" name="search" placeholder="Search Doctors" 
          onClick={() => {
            this.onProviderListing(this.state.skip,0);
            this.onEnable();
                  }}
          onChange={() =>this.onSearchProvider(this.state.skip,0)} />

This is the function where I need the onchange value:

onSearchProvider(nSkip,nLimit,e){
      this.setState({
        limit:nLimit,
        skip:nSkip,
        listing: this.state.listing,
        searching: !this.state.searching
      })
      //console.log(nlimit);
      var headers = {
        "Content-Type":"application/json",
        "AccessToken":localStorage.TOKEN,
      }
      var _calObj = {initiatorId:localStorage.userid,visitType: "office", skip:nSkip,limit:"5", includeOfflineProviders:"true",searchQuery:"lo"}

I need to pass my input values in the search query onchange accordingly. Can you help me resolve this?

Answer №1

Make sure to include the event parameter in your input onChange function. Here's how you can update it:


       <input className="ReactSearchBox" name="search"
          placeholder="Search Doctors" 
          onClick={() => {
            this.onProviderListing(this.state.skip,0);
            this.onEnable();
                  }}
          onChange={(e) =>this.onSearchDataUpdate(this.state.skip,0, e)}
        />

onSearchDataUpdate(skip, limit, e){
  const inputValue = e.target.value; // retrieve text box value
}

Answer №2

You have the option to enhance the onChange function in jsx by including the e event object like this:

onChange={(e) => this.onSearchProvider(this.state.skip,0,e)}

In the onSearchProvider method, you can then access it as shown below:

onSearchProvider(nSkip, nLimit, {target}){
   // The search box text will be displayed here on change
   console.log(target.value) 
}

Answer №3

When it comes to the onChange method, passing state values is unnecessary.

The state remains consistent within the component.

<input className="ReactSearchBox" name="search" placeholder="Search Doctors" 
     onChange={() =>this.onSearchProvider(0)}
/>

You can easily retrieve the input value using `event.target.value`.

onSearchProvider(nLimit,e){
  // You can access state values directly here like this.state.skip
  const searching = e.target.value;
}

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

Dividing an AngularJS module across multiple iFrames on a single webpage

Currently, I am working on a web application that consists of 1 module, 5 pages, and 5 controllers. Each HTML page declares the same ng-app. These pages are loaded within widgets on a web portal, meaning each page is loaded within an iFrame in the portal. ...

Guide to developing an input field with increase and decrease buttons in React Native

Looking to add increment and decrement buttons to an input field in a React Native project. I need something similar to the example shown here: https://i.stack.imgur.com/61m45.jpg This is my first time working with React Native. ...

Securely encoding information with PHP and decrypting it using JavaScript

I'm currently working with 2 servers. My goal is to generate a pair of keys, store the private key in local storage, and send the public key to my PHP server. The main objective is to encrypt data using the public key in PHP and decrypt it using Jav ...

Personal Information Management

After making a request for stormpath user custom data, I used the following code: res.render('home', { title: 'home', user: req.user.customData, }); Instead of receiving a JSON object of custom data as expected, a URL ('') ...

Stylish hover effects displayed on disabled button using Styled Components

I am currently working on a button using Styled Components. However, even when the button is in a disabled state (:disabled), it still exhibits hover behavior that should not be present. I am wondering if there is a proper way to prevent hover effects when ...

Is it possible to modify the spacing of menu items in the React Material-ui Drawer component?

Recently, I decided to incorporate Material-UI into a React project for the first time. The AppBar was set up to trigger Drawer, which displayed a list of menu items in the sidebar. However, an issue arose with excessive margin-top spacing. Here is an ill ...

Using Javascript to make a call to a RESTful endpoint

My current challenge involves attempting to make a call to the Spotify API from JavaScript: function callAPI() { var xhttp = new XMLHttpRequest(); xhttp.open('GET', 'https://api.spotify.com/v1/search?q=Muse&type=track'); ...

A collection of items that mysteriously affix themselves to the top of the page as

Unique Context In my webpage, I have a specific div element with the CSS property of overflow: auto. Within this scrolling div, there is structured content like this: <h3>Group A</h3> <ul> <li>Item 1</li> <li>I ...

Overflow due to cascading style sheets

THE ANSWER TO THIS QUESTION HAS BEEN PROVIDED In regards to this particular div that contains two unordered lists, I am seeking a solution where these lists can be positioned side by side instead of above or below each other. I have attempted various met ...

When using JavaScript to redirect with window.location, the referrer header is not properly set

Currently, I am attempting to utilize window.location in React to redirect to a third-party page. However, upon making the redirect, the third-party server is not receiving a referrer header from my redirection. Any assistance on resolving this issue wou ...

Exploring the limitations of middlewares in supporting independent routers

When I examine the code provided, it consists of three distinct routers: const Express = require("express") const app = Express() // Three independent routers defined below const usersRouter = Express.Router() const productsRouter = Express.Router() cons ...

Adding a unique key to every element within a JavaScript array

I am working with the array provided below which contains simple values. My goal is to add a key id before each value in the array, resulting in something like this: ["id:a", "id:b","id:c","id:d"]. Is there an easy way to achieve this? Any assistance would ...

Changing the order of element names depending on their location within the parent element using jQuery

<div class="content"> <div> <input type="text" name="newname[name]0"/> <div> <input type="text" name="newname[utility]0"/> <div> <textarea name="newname[text]0 ...

display information with html

Encountered an error while attempting to display data using HTML: https://i.stack.imgur.com/vRXL3.png This is the code in question : <?php echo form_open("dashboard/edit_product/$product_id");?> <div class="form-group"> <div c ...

Why is the picture not showing up on the screen?

import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import GridList from '@material-ui/core/GridList'; import GridListTile from '@material-ui/core/GridListTile'; import tileData from &ap ...

Turning off v-navigation-drawer for certain routes in Vue.js

I currently have a v-navigation-drawer implemented in my webpage using the code below in the App.vue file. However, I am looking to disable it on certain routes, such as the landing page: <v-app> <v-navigation-drawer id ="nav" persistent : ...

Creating JEST unit tests for a basic functionality

Here is the React code I have written: getDetails: function () { var apiUrl = ConfigStore.get('api') request .get(apiUrl) .set('X-Auth-Token', AuthStore.jwt) .set('Accept&apo ...

Show a pop-up form when a user focuses on it using React

Hello, I have been looking for a way to create an overlay with a form that appears when a specific input field is clicked. I am trying to achieve this using React. Can someone please advise me on how to accomplish this? Here is my code import React, { Co ...

Stop users from saving the page in Next.js

I'm currently working on a NextJs project that involves building an editor application. I want to ensure that the editor functionality does not work when users attempt to save the page in a different format, similar to how applications like Youtube an ...

I noticed that my API call is being executed twice within the router function

In my NextJs project, I am utilizing Express for routing. I have implemented a router with a dynamic :id parameter which triggers an axios call to check the ID in the database. However, I am facing an issue where the API is being called twice when the :id ...