Allow the select option to be clicked, while preventing it from automatically filling the select input field in reactstrap's Input component

I have a select with an option called "+ Create new"

When the user clicks on this option, I am displaying a modal to create a new option. However, I do not want this select option to show "+ Create new" after it is clicked.

How can I make the option "clickable" but prevent it from appearing in the select's actual input view?

Here is the component:

import React, {useState} from 'react';
import { Input } from 'reactstrap'

const TestComponent = () => {

  const [upload, setUpload] = useState({
    selectHeader: []
  })

  const [showFieldModal, setShowFieldModal] = useState(false);

  return (
              <Fragment>
                <Input
                  type="select"
                  name="selectHeader"
                  id="selectHeader"
                  onChange={({ target }) => {
                    if(target.value === "+ Create new") {
                      setShowFieldModal(!showFieldModal)
                    } else {
                      setUpload({...upload, selectHeader: [...upload.selectHeader, {value: target.value, index: index}]})
                    }
                  }}
                 >
                   <option>First name</option>
                   <option>Last name</option>
                 
                    <option>+ Create new</option> <!-- make this clickable but don't allow it to be shown as the select's option when clicked -->
                 </Input>
                </Fragment>
);
};

export default TestComponent;

The code below considers the accepted answer and adds functionality for mapping over an array and rendering multiple Inputs with type="select" that do not display the "+ create new" option:

Note: the id is updated to .id={`selectHeader${index}`} and the onChange is updated to

document.getElementById(`selectHeader${index}`).value= "";

<Table responsive bordered striped hover>
      <thead>
        <tr>
          {
            fileContacts.map((contact, index) => (
                <th className="bg-primary pr-1 pl-1 pt-2 pb-2 overflow-hidden" scope="col" key={index}>
                  <Input
                  type="select"
                  className="fs--1"
                  name="selectHeader"
                  id={`selectHeader${index}`}
                  onChange={({ target }) => {
                    
                    if(target.value === "+ Create new") {
                      document.getElementById(`selectHeader${index}`).value= "";
                      setShowFieldModal(!showFieldModal)
                    } else {
                      setUpload({...upload, selectHeader: [...upload.selectHeader, {value: target.value, index: index}]})
                    }
                  }}
                 >
                   
                   <option>First name</option>
                   <option>Last name</option>
                  
                 { fields.map((field, index) => (
                   <option key={index} >{field.title}</option> 
                 ))}
                    <option>+ Create new</option>
                 </Input>
                </th>  
          ))}
        </tr>
      </thead>
      <tbody>
        {
        upload.contacts.slice(0, 10).map((customer, index) => (
          <TableRow data={customer} key={index}/>
        ))
        }
      </tbody>
    </Table>

Answer №1

One possible solution is to clear the select value after selecting an option. You can try implementing this approach:

onChange={({ target }) => {
     if(target.value === "+ Add new") {
        document.getElementById('selectHeader').value= " " ;
        setShowFieldModal(!showFieldModal)
     } else {
        setUpload({...upload, selectHeader: [...upload.selectHeader, {value: 
        target.value, index: index}]})
     }
}}

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

How to correctly serialize nested maps in JQuery ajax data for sending?

var locationData = { "location" : { "name" : $("#user_loc_name").val(), "street_address" : $("#user_loc_street_address").val(), "city" : $("#user_loc_city").val(), "province" : ...

What is the method to close the picker when using type="datetime-local"?

Currently, I am utilizing Vue with the "datetime-local" type for input. While I can successfully select the date and time, my goal is to have the picker close automatically after a selection has been made. I've experimented with adding an onchange ev ...

Preventing circular dependencies while upholding the structure of modules in Express

I am developing an express app in ES6 and organizing my files by functionality. In this structure, each module has an index.js file that is responsible for exporting relevant methods, classes, etc. Other modules simply require the index.js from another mod ...

Receiving "this" as an undefined value within the TypeScript class

Currently developing a rest api using express.js, typescript, and typeorm. Initially thought the issue was with AppDataSource, but it seems to be functioning properly. Below is my controller class: import { RequestWithBody } from '@utils/types/reque ...

The grouping of values in JavaScript is known as an array

I need assistance in modifying my code to generate dynamic buttons based on array elements instead of objects. Currently, the array I am using contains objects which is causing issues with tracking button status and other computations. Can you help me adju ...

Pass the $scope object from a controller to a modal controller

I am facing an issue with transferring the $scope variable from ctrlone to ctrltwo, which is a modal window on my page. When I open the modal in ctrlone, my code looks like this: var modalInstance = $modal.open({ templateUrl: 'Modal.html&ap ...

How to use bootstrap to resize and center a div element

I'm struggling with formatting a form that is enclosed in a bordered fieldset. Currently, all the form fields are filling the entire width of the fieldset. However, I want certain textfields to be shorter and centered within the fieldset. I have attem ...

Text area featuring unique border design, with border color change upon focus?

Currently, I have a text area with borders that are designed in a unique way. However, I am looking to change the border color when the user focuses on the text area. Do you have any suggestions on how I can achieve this effect without affecting the curre ...

Guide on incorporating a slash into a React Router path

I have just finished creating a new page using React, and the route for this page is: http://example.com/page1 Upon loading the URL, I realized the need to add a slash at the end like so: http://example.com/page1/ The routes in my code look like this: ...

Retrieve the variable from a function that is invoking the export.modules in node.js

How can I extract the code from the randomCode() function in the users.js file, assign it to the result variable, and use it throughout the entire '/login' endpoint? randomCode.js const crypto = require('crypto') const randomCode = (c ...

Having trouble with my sorting algorithm - am I overlooking something obvious?

function Controller($scope) { var sortItems = [ { "text": "Second", "a": 2 }, { "text": "Fifth", "a": 5 }, { "text": "First", "a": 1 }, { "text": "Fourth", "a": 4 }, { "text": "Third", "a": 3 } ]; va ...

The correct method for implementing server-side rendering with JavaScript

My website consists of multiple pages and utilizes React as a widget toolkit, with different bundles on each page. I am facing an issue where some widget state persists within a login session, and when the user revisits the page, the components should relo ...

The presence of floats in CSS influence the surrounding div elements

Currently experimenting with HTML/CSS utilizing Bootstrap v5.0 and encountering issues with the unusual interactions between floats and divs. Specifically, aiming to achieve the following: https://i.sstatic.net/4lpC2.png Successfully achieved the desired ...

Encountering a Parsing error while utilizing redux: Unexpected token present

Trying to implement Redux for managing the searchField state on the website. After creating action.js, reducer.js, constant.js, and redux.connect() function, An error occurred: Parsing error: Unexpected token 62 | return <div className=&apo ...

Exploring the differences between JavaScript destructuring and assignment

In my code, I initially used this line: const availableDays = status.availableDays; However, a suggestion was made to replace it with this line: const { availableDays } = status; Both options achieve the same result in one line of code, but I am curious ...

Determine the value from an object in the view by evaluating a string in dot notation

Seeking assistance with a recurring issue I've encountered lately. Imagine having two objects in AngularJS: $scope.fields = ['info.name', 'info.category', 'rate.health'] $scope.rows = [{ info: { name: "Apple", cate ...

Methods for dynamically populating dropdown lists with JavaScript and Bootstrap

I have collected all 387 regions for the current date and now I want to dynamically populate a bootstrap dropdown with these regions using JavaScript. Below is the basic HTML code for a bootstrap dropdown: <div class="dropdown"> <button class ...

Loading drop-down menu content after making an AJAX request

I understand that AJAX functions asynchronously (hence the "A" in AJAX). I have placed all the code that relies on the result of the AJAX call inside the success callback function. However, even after making the call, the select dropdown box is not being p ...

What is the rationale behind TypeScript's decision to permit omission of "this" in a method?

The TypeScript code below compiles without errors: class Something { name: string; constructor() { name = "test"; } } Although this code compiles successfully, it mistakenly assumes that the `name` variable exists. However, when co ...

What sets apart the JavaScript console from simply right-clicking the browser and opting for the inspect option?

As I work on developing an angular application, one of my tasks involves viewing the scope in the console. To do this, I usually enter the code angular.element($0).scope(). This method works perfectly fine when I access the console by right-clicking on th ...