Tips for showcasing the chosen option from an autocomplete input field in a React application

Currently learning React and working on a search feature for a multi-form application. The goal is to allow users to search for a student by first name, last name, or student ID using an autocomplete text field.

The options for the autocomplete text fields are successfully passed and displayed when the cursor is in the text field. However, typing or selecting a value does not change the content of the text field as expected.

Here is the code snippet:

<Autocomplete
        id="auto-complete"
        options={values.suggestions}
        getOptionLabel={option => option.stuId+" "+ option.fName+" "+option.lName}
        autoComplete
        includeInputInList
        fullWidth
        renderInput={params => (
           <TextField {...params}  margin="normal" fullWidth />)}
        />

The values are being passed through props.

The desired outcome is to update the 'searchKeyword' state with the selected student's stuId and have it displayed in the autocomplete text field. Are there any onChange or default value functions that I could use to achieve this?

Answer №1

Do you think this is the solution you need?

<Autocomplete
  ...
  value={this.state.value}
  onChange={(event, value) => this.setState({ value })}
  ...
/>

Answer №2

You can access the value of the selected option in hooks


/* eslint-disable no-use-before-define */
import React, { useState } from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";

export default function ComboBox() {
  const [selectedOption, setSelectedOption] = useState("");
  return (
    <Autocomplete
      id="combo-box-demo"
      options={top10Films}
      getOptionLabel={(option) => option.title}
      style={{ width: 300 }}
      value={selectedOption}
      onChange={(e, v) => {
        setSelectedOption(v);
      }}
      renderInput={(params) => (
        <TextField {...params} label="Combo box" variant="outlined" />
      )}
    />
  );
}

// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top10Films = [
  { title: "The Shawshank Redemption", year: 1994 },
  { title: "The Godfather", year: 1972 },
  { title: "The Godfather: Part II", year: 1974 },
  { title: "The Dark Knight", year: 2008 },
  { title: "12 Angry Men", year: 1957 },
  { title: "Schindler's List", year: 1993 },
  { title: "Pulp Fiction", year: 1994 },
  { title: "The Lord of the Rings: The Return of the King", year: 2003 },
  { title: "The Good, the Bad and the Ugly", year: 1966 },
  { title: "Fight Club", year: 1999 }
];



Check out this codesandbox for reference: https://codesandbox.io/s/restless-meadow-hj0em?fontsize=14&hidenavigation=1&theme=dark

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

Is there a way to access an SD card by clicking on an HTML link using JavaScript?

UPDATE: I am seeking a way to embed an HTML file with JavaScript or jQuery that can directly access the contents of the SD card while being opened in a browser. Currently, I have posted code for accessing it through an activity, but I want to be able to d ...

Discover multiple keys within a new Map object

Our usual approach involves creating a new Map like this: const hash = new Map() hash.set(key,value) To retrieve the information, we simply use: hash.get(specificKey) An advantage of using Map is that we have flexibility in choosing keys and values. Cur ...

What are the steps to manipulate the data within an EJS file after passing an array through Node.js as an object?

I'm currently developing a simple calendar application using Node.js and ejs. I am working on passing an array of months through express to my ejs file, with the goal of being able to cycle through each month by clicking the next button. How can I imp ...

Having Trouble with $.ajax Function in my Program

After spending three days experimenting with various methods, I'm still unable to successfully use the Javascript ajax command to send form values to a php script. Despite no errors being displayed and the scripts running smoothly, nothing is getting ...

Console output shows that the function results in undefined

When I pass a string parameter to a function, I expect the console to display "reff", but it is showing "undefined" instead. Here is the code snippet: var _ref; function foo(_ref='reff') { var bar = _ref.bar; return console.log(bar); } foo ...

Despite setting `staleTime` to Infinity, React Query continues to trigger refetches

export function retrieveAllUsers() { return useQuery<UserResponseDto[]>({ queryKey: [QueryClientKeys.GET_ALL_USERS], queryFn: async () => { const response = await http.get< UserResponseDto[], ...

Develop a unique Kotlin/JS WebComponent featuring custom content

I am trying to create a custom tag using Kotlin that includes default content. While the example I found works well, I am having trouble adding default content (such as an input element) inside the custom tag. After attempting various approaches, I have o ...

"Enhance your web application with Material UI's powerful dat

Hey there, I've got a couple of questions about the Material UI - datagrid filter with type:dateTime. Is there a way to change the local format when selecting the date in the filter? It currently displays the AM/PM date format and I can't seem t ...

Discovering the RootState type dynamically within redux toolkit using the makeStore function

I am currently working on obtaining the type of my redux store to define the RootState type. Previously, I was just creating and exporting a store instance following the instructions in the redux toolkit documentation without encountering any issues. Howev ...

attaching the model to chosen values rather than defining the chosen item

This is the coding I am currently using which is functioning correctly: <div class="col-md-12"> <div class="button-group"> <button type="button" class="btn btn-default btn-block btn-sm dropdown-toggle" data-toggle="dropdown"> ...

What is the best way to incorporate JavaScript code as React syntax?

For my project, I am using the OpenLayers API Map. I'm unsure of the correct way to incorporate JavaScript code in React or vice versa. Here is an answer on how to use markers in the map, but I am struggling to implement it in my current code since I ...

jQuery error: an unexpected token was encountered

I am encountering an issue with an "unexpected token =" error on the line toggleNav = function(evt){ in the code snippet below. Despite going through various similar posts, I am unable to pinpoint why this error is occurring. Any assistance in guiding me ...

Creating dynamic animations for your elements with AJAX

How can I apply animation to an element as soon as it appears? I want others with the same properties to remain unaffected. Here is my approach: $.each(data, function(i, obj) { if(obj['Ping'] == "FALSE"){ ...

Error encountered with TypeScript compiler when using a React Stateless Function component

I am attempting to create a React Stateless Function component using TypeScript. Take a look at the code snippet below: import * as React from 'react'; import {observer} from 'mobx-react'; export interface LinkProps { view: any; ...

javascript code not functioning properly

Something simple! In my asp.net-MVC project, I have a button and an external JavaScript file called mydata.js. This file contains a function called checkJS(). function checkJs() { debugger; alert("your output!!!"); } Here is my code: <div id="m ...

Generating documents in Word or PDF format using PHP and Angular data

My goal is to generate a Word document using PHP for which I found a solution involving the use of headers. header("Content-type: application/vnd.ms-word"); header("Content-Disposition: attachment;Filename=output.doc"); Initially, this method worked well ...

What is the best way to halt a window.setInterval function in JavaScript?

I have a JavaScript function that runs every 2000ms. I need to find a way to pause this function so that the user can interact with other elements on the page without interruptions. Is there a way to achieve this? Below is the code for the function: win ...

JavaScript functions with similar parent names

Explain a function that has identical functionality to its parent parent.document.getElementById(source).innerHTML should be the same as other-function-name.document.getElementById(source).innerHTML ...

Exploring the functionality of window.matchmedia in React while incorporating Typescript

Recently, I have been working on implementing a dark mode toggle switch in React Typescript. In the past, I successfully built one using plain JavaScript along with useState and window.matchmedia('(prefers-color-scheme dark)').matches. However, w ...

Serve the JS files in Express separately

I am facing issues with my webapp loading too slowly when using the express.static middleware to serve all my js files. I am considering serving each js file only when needed, such as when serving the html from jade that uses the js file. I have attempted ...