Adding a custom type to a selected option for the onChange event in React-Select can be done by modifying the

After creating a SelectBox component using react-select and applying onChange event to it, I encountered an issue. I wanted to include a type "SelectedItemType" to the selected option in the onChange event, but the property of onChange was defined as (property) onChange?: ((newValue: unknown, actionMeta: ActionMeta) => void) | undefined. This resulted in the option type being unknown, making it challenging to extract object attributes from the option.

import { ForwardedRef, forwardRef } from "react";
import Select, { SelectInstance } from "react-select";

export type SelectedItemType = {
value: string;
label: string;
};

export type SelectProps = {
options: SelectedItemType[];
ref?: ForwardedRef<SelectInstance>;
onChange: (selectedItem: unknown) => void;
};

const SelectBox: React.FC<SelectProps> = forwardRef<
SelectInstance,
SelectProps
>(({ options, onChange, ...props }, ref) => {
return (
<Select
options={options}
ref={ref}
{...props}
onChange={(newValue: unknown) => onChange(newValue)}
/>
);
});

export default SelectBox;

In the above code snippet, my aim was to add SelectedItemType to the newValue for onChange. However, I encountered an error stating that Type '(newValue: SelectedItemType) => void' is not assignable to type '(newValue: unknown, actionMeta: ActionMeta) => void'. The types of parameters 'newValue' were found to be incompatible, with 'unknown' not matching with 'SelectedItemType'. How can I successfully integrate this custom Type to the option in order to extract the value and label?

Answer №1

If you wish to define the type of newValue as SelectedItemType in order to easily access its properties in the onChange function, you can make two key changes.

  1. Update the type of the onChange property in the SelectProps as follows:
export type SelectProps = {
  options: SelectedItemType[];
  ref?: ForwardedRef<SelectInstance>;
  onChange: (selectedItem: SelectedItemType) => void;
};
  1. In the select component, modify its onChange like this:
<Select
      options={options}
      ref={ref}
      {...props}
      onChange={(newValue: unknown) => onChange(newValue as SelectedItemType)}
    />

Now, utilize your SelectBox component as shown below:

<SelectBox
        options={[
          { label: "A", value: "1" },
          { label: "B", value: "2" }
        ]}
        onChange={function (selectedItem: SelectedItemType): void {
          console.log(selectedItem.value);
        }}
      />

Below is the complete code for the file App.tsx:

import { ForwardedRef, forwardRef } from "react";
import Select, { SelectInstance } from "react-select";

export type SelectedItemType = {
  value: string;
  label: string;
};

export type SelectProps = {
  options: SelectedItemType[];
  ref?: ForwardedRef<SelectInstance>;
  onChange: (selectedItem: SelectedItemType) => void;
};

const SelectBox: React.FC<SelectProps> = forwardRef<
  SelectInstance,
  SelectProps
>(({ options, onChange, ...props }, ref) => {
  return (
    <Select
      options={options}
      ref={ref}
      {...props}
      onChange={(newValue: unknown) => onChange(newValue as SelectedItemType)}
    />
  );
});

export default function App() {
  return (
    <div className="App">
      <SelectBox
        options={[
          { label: "A", value: "1" },
          { label: "B", value: "2" }
        ]}
        onChange={function (selectedItem: SelectedItemType): void {
          console.log(selectedItem.value);
        }}
      />
    </div>
  );
}

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

Can the return type of a function be determined dynamically at runtime by analyzing a function parameter value?

Let's delve into this concept with an illustrative example! interface Query { foo: any; } interface Mutation { bar: any; } type OperationName = keyof Query | keyof Mutation; const request = async <T>(args, operationName: OperationName): P ...

Using redux action in the onPaginationChange function instead of setPaginationState in the given example for the TanStack table - is there a way to

Provided this sample Is there a way to utilize by dispatching a redux action rather than using useState - setPaginationState? onPaginationChange: state => dispatch(browseItemModalActions.setPagination(state)) An error is appearing in the console: ...

Limiting the number of items shown in the dropdown panel of an NgSelect

Currently, I am utilizing Angular ngselect to showcase a dropdown menu with multiple options. However, due to the limited screen space, I need to restrict the number of items visible in the dropdown to about 3, allowing users to scroll through the rest. W ...

Utilizing Express-WS app and TypeScript to manage sessions

I am currently working on setting up a node server using Typescript with the help of express and express-ws. My goal is to include Sessions in my application, so I have implemented express-session. Below you can find some pseudo code: import * as session ...

Resolving a persistent AngularJS 1 constant problem with Typescript

I'm currently developing an application using TypeScript and AngularJS 1, and I've encountered a problem while trying to create a constant and passing it to another class. The constant in question is as follows: module app{ export class A ...

Steps for transitioning a VUE JS project to TypeScript

Is it possible to transition a VUE JS project from JavaScript to TypeScript without rewriting everything? I heard from a friend that it can be done through the VUE CLI, but I haven't been able to find any documentation or articles on this method. Has ...

Error: Idle provider not found in the promise

Currently, I am integrating ng2-idle into an AngularJS 2 application. After successfully including the ng2-idle package in the node_modules directory of my project, I attempted to import it into one of my components as shown below: Dashboard.component.ts: ...

Tips for scrolling ion-items vertically to the bottom and top using arrow icons in Ionic 4

I'm developing an Ionic 4 app with Angular and looking to incorporate Up and Down Arrow buttons for vertical scrolling from top to bottom and vice versa. ...

Is there a way to extract a specific item from a ListView by tapping on it in Nativescript?

Attempting to retrieve data from a tap event using angular2 + typescript: This is the html code for the component: <RadListView row="1" [items]="groceryList" [class.visible]="listLoaded" (tap)="seeItem($event)" swipeActions="true" (itemSwipeProgr ...

What is the error message "Cannot assign type 'IArguments' to argument"?

Currently employing a workaround that is unfortunately necessary. I have to suppress specific console errors that are essentially harmless. export const removeConsoleErrors = () => { const cloneConsoleError = console.error; const suppressedWarnings ...

Mistakenly importing the incorrect version of Angular

While working on my Angular 1 app in typescript, I faced an issue when importing angular using the following syntax: import * as angular from 'angular'; Instead of importing angular from angular, it was being imported from angular-mocks. Thi ...

Executing an asynchronous function within an Angular 7 interceptor is crucial

I've been working on creating an interceptor to handle a situation where a function needs to be called to refresh the session upon receiving a 401 error response. Here's what I have so far but I'm facing build issues and struggling to figure ...

Using ReactJS with Material UI and applying styles with withStyles including themes in TypeScript

I've been working on converting the Material UI Dashboard into TypeScript. You can find the original code here: Material UI Dashboard One issue I'm encountering is that I am unable to define CSS styles within the withStyles function while export ...

Learn how to dynamically activate an icon in Angular to enhance user interaction

HTML Code: The Zoom Component <div class="zoom py-3"> <i nz-icon nzType="minus" (click)="zoomToggle(false)" nzTheme="outline"></i><br> <i nz-icon nzType="plus" (click)=&q ...

Angular's array filter functionality allows you to narrow down an

I am working with an Array and aiming to filter it based on multiple criteria: primasSalud = [ { nombre: 'one', internacional: true, nacional: false, nacionalSinReembolso: false, nacionalClinicasAcotadas: false ...

What is causing certain code to be unable to iterate over values in a map in TypeScript?

Exploring various TypeScript idioms showcased in the responses to this Stack Overflow post (Iterating over Typescript Map) on Codepen. Below is my code snippet. class KeyType { style: number; constructor(style) { this.style = style; }; } fu ...

Compilation of Angular 6 project is failing due to error TS1005: Expected ',' instead of the symbol used

I keep encountering an error message whenever I try to compile my code. ERROR in src/app/form/form.component.ts(22,39): error TS1005: ',' expected. Below is the snippet of code where the error is pointing: import { Component, OnInit } from &ap ...

Error encountered with the root reducer due to data type mismatch

Within my Redux store setup, I have a persistedReducer initialized to include the redux-persist config and the "rootReducer": client/src/redux/store.ts: import { configureStore } from '@reduxjs/toolkit'; import { persistStore, persistReducer } f ...

What are some effective strategies for utilizing observables for handling http requests in an Angular application?

In my Angular application, I am retrieving data from APIs. Initially, my code in detail.component.ts looked like this: //code getData() { this.http.get(url1).subscribe(data1 => { /* code: apply certain filter to get a filtered array out */ t ...

Guide to resolving the issue of error Type 'void[] | undefined' cannot be assigned to type 'ReactNode'

I am attempting to map the data Array but I am encountering an error: Type 'void[] | undefined' is not assignable to type 'ReactNode'. Can someone please assist me in identifying what I am doing wrong here? Below is the code snippet: i ...