What is the best method to reset the chosen option in a dynamic select dropdown using React?

I have a form set up with a Select dropdown that is populated dynamically from the server.

The issue I'm facing is that after selecting an option from the dropdown and then saving or canceling the form, the selected value remains in the field when I reopen the form.

How can I fix this problem? Here's my code:

 class Task extends Component{
   constructor(props){
      super(props);
      this.state={
        SelectedName:'',
        TaskList:[],
       }
    }
  
 componentWillMount(){
 fetch(
 ...
   .then(responseJson => {
       let taskList=responseJson.data;
       let r = taskList.map(function(task){
            return {value: task.id, display: task.name}
          });
       this.setState({TaskList:r });
 }

//this is cancelForm fucntion
  cancelSave=()=>{
     this.setState({SelectedName:''});
   }

handleNameSelection=()=>{
 var row = this.state.TaskList.filter(function (item) {
            return item.value == event.target.value
         })
 this.setState({ SelectedName: row[0].display});
}

 render(){
   return(
    <Select
         defaultValue="placeholder-item"
         id="select-task-name"
         labelText="Select Task Name"
         value={this.state.SelectedName}
         onChange={(event) => this.handleNameSelection(event)}
       >
              {
                (this.state.TaskList.length > 0) ?
                  this.state.TaskList.map(function (list, idx) {
                    return <option key={idx}
                      value={list.value}>{list.display}</option>
                  })
                  :
                  <option />
              }
            </Select>

    );

  }
 }

Answer №1

Remember to clear the array list of tasks in the state once your form has been submitted

If you are having trouble finding the submit function, make sure it is not being used as a subcomponent. If so, you will need to implement a different logic. Otherwise, refer to the example below:

let onSubmit = (values) => {
   /* code for submitting the form */

   this.setState({
      ...state,
      SelectedName: ''
   });

}

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

Adjust item size and move them into the panel

I am looking to create a panel that arranges items in a specific layout shown here: https://i.stack.imgur.com/qw3lS.png Below is the code I have attempted so far: import React, { useCallback, useEffect } from "react"; import { Box, Grid, Tab, T ...

Analyze the information presented in an HTML table and determine the correct response in a Q&A quiz application

I need to compare each row with a specific row and highlight the border accordingly: <table *ngFor="let Question from Questions| paginate: { itemsPerPage: 1, currentPage: p }"> <tr><td>emp.question</td></tr> <tr> ...

What effect does setting AutoPostBack to "true" in an ASP dropdownlist have on the fireEvent() function?

I am currently working on an aspx page. This page includes three dropdown lists and a button, all of which are populated dynamically based on the code written in the code-behind file (.cs file). To achieve this, I need to utilize two event handler methods ...

Identify the Google Maps Marker currently displayed on the screen

Is there a way to generate a list of markers within the zoom range for Google Maps, similar to the functionality on this site I'm curious if I can achieve this using jQuery or if there is a built-in function for Google Maps v3? Thank you! ...

Is it necessary for the scope to be separated?

In the document object model (DOM), I have two straightforward directives that are responsible for creating similar elements. Both directives have an isolated scope. Each directive has an ng-click attribute that calls a method to display a message. One d ...

The 'name' property of Axios and Vuex is not defined and cannot be read

When making a call to axios in my mounted function to retrieve profile data, I send the payload to the 'set_account' Vuex store upon success. To access this data, I utilize MapGetters (currentAccount) in computed properties. However, when tryin ...

What is the best way to add selected values from a multi-select dropdown into an array?

Attempting to populate an array from a multiple select dropdown, I've encountered an issue. Despite using splice to set the order of values being pushed into the array, they end up in a different order based on the selection in the dropdown. For insta ...

Problems during the installation of Webpack

Encountering Error Setting up Webpack and Babel with NPM npm ERR! Unexpected end of JSON input while parsing near '...pdragon":"^0.7.0","to' npm ERR! A complete log of this run can be found in: npm ERR! A complete log of this run can be found ...

When a Javascript function marked as async is executed, it will return an object

Async function is returning [object Promise] instead of the desired real value. Interestingly, I can see the value in the console log. It seems like this behavior is expected from the function, but I'm unsure how to fix my code. This code snippet is ...

Manipulate Attributes in Javascript

Having an issue here - I'm trying to use JavaScript to set some attributes. for(i=0;i<div_navi.childNodes.length;i++){ if(div_navi.childNodes[i].nodeName =="SPAN"){ div_navi.childNodes[i].setAttribute("onclick","g ...

What is the best way to modify the glyphicon within the anchor tag of my AJAX render property?

Consider the use of Ajax: "target 0" with a render option for an anchor tag. Initially, I am utilizing the class "glyphicon glyphicon-chevron-right". Now, I wish to change it to "glyphicon glyphicon-chevron-down" when clicked. $(document).ready(funct ...

How to eliminate spaces while preserving line breaks in a textarea using JS or jQuery

I have been trying to figure out how to remove extra spaces from the beginning and end of lines while keeping the line breaks intact. Here's what I attempted: function removeSpaces(string) { return string.split(' ').join(''); } ...

What is the best practice for using templates in a constructor versus connectedCallback?

Should I apply template in the constructor or connectedCallback of a custom element? In my experience, when I apply it in connectedCallback, sometimes attributeChangedCallback is called before and I can't query for elements. export class TestElement ...

Acquire an array of Worksheet names in JavaScript by utilizing ActiveX

How can I retrieve a comprehensive list of all available sheet names from my Excel file using the ActiveX Object? I am aware that the code Excel.ActiveWorkBook.Sheets provides access to the sheets. However, how do I obtain an array containing the NAMES of ...

Button to save and unsave in IONIC 2

I am looking to implement a save and unsaved icon feature in my list. The idea is that when I click on the icon, it saves the item and changes the icon accordingly. If I click on it again, it should unsave the item and revert the icon back to its original ...

Interacting with external domains through ajax queries

I'm encountering an issue with my javascript code that sends an ajax request, but I'm not receiving any response. Can anyone offer some guidance on how to troubleshoot this problem? Thank you! The URL I am attempting to retrieve is: Here's ...

The implementation of a custom event for jQuery rows is not functioning as expected

I need assistance with jQuery code to add click events only to columns in a row that have text in the first column. Specifically, I want to hide rows containing "1/" in the first column when clicked on for the first row. <table class="results"> < ...

"Successfully rendering the map on the initial load, but encountering an error of 'cannot map undefined'

Having trouble displaying data retrieved from an API. Initially, the movie titles are shown without any issues. However, upon refreshing the page, an error message stating "cannot map undefined" appears. Here is the code snippet: const [media, set ...

Organizing JSON keys based on their values using Typescript

In the context of a main JSON structure represented below, I am interested in creating two separate JSONs based on the ID and Hobby values. x = [ {id: "1", hobby: "videogames"}, {id: "1", hobby: "chess"}, {id: "2", hobby: "chess ...

Multi-object retrieval feature in Material Dialog

I am encountering an issue with Material Dialog when confirming the action to "remove row" in a table. Initially, removing from the dialog works fine and deletes a row. However, after closing the dialog and re-calling it for the second time, the removal ac ...