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

Adding a fresh element to an object array in TypeScript

How can we add a specific value to an array of objects using TypeScript? I am looking to insert the value 1993 into each "annualRentCurrent" property in the sample object. Any suggestions on how to achieve this in TypeScript or Angular? Thank you! #Data ...

How can I use TypeScript to wrap a component in Vue 3?

Looking to customize a PrimeVue component (Calendar) by styling it differently and then re-exporting it. Here's an example in React: const WrappedCalendar: React.FC<CalendarProps> = (props)=> <div style={{background:'green'}}&g ...

Create and export a global function in your webpack configuration file (webpack.config.js) that can be accessed and utilized

Looking to dive into webpack for the first time. I am interested in exporting a global function, akin to how variables are exported using webpack.EnvironmentPlugin, in order to utilize it in typescript. Experimented with the code snippet below just to und ...

What could be causing my controller method in TypeScript to throw an error message unexpectedly?

Hey there. I'm diving into TypeScript and currently working on converting an Express backend to TS. Everything was smooth sailing until I encountered some unexpected issues. Specifically, the lines const hasVoted = poll.votedBy.some((voter): boolean = ...

Transforming JSON data into an Angular TypeScript object

Delving into the realm of Angular on my own has been quite an enlightening journey, but I'm currently facing a specific issue: My aim is to create a website using both Spring for the back end and Angular 7 for the front end. However, I've encoun ...

The function is trying to access a property that has not been defined, resulting in

Here is a sample code that illustrates the concept I'm working on. Click here to run this code. An error occurred: "Cannot read property 'myValue' of undefined" class Foo { myValue = 'test123'; boo: Boo; constructor(b ...

Issue: NG04002 encountered post migration from Angular to Angular Universal

Having recently created a new Angular app and converted it to Angular Universal, I encountered an issue when running the project using npm run dev:ssr. The error displayed in the terminal is as follows: ERROR Error: Uncaught (in promise): Error: NG04002 Er ...

Enrich your TypeScript code by unleashing the power of enum typing in overloading logical

I have a custom enum called PathDirection that represents different directions export enum PathDirection { LEFT="LEFT"; RIGHT="RIGHT"; }; Within my code, I need to toggle between the two directions. For example: let currentDire ...

What is the method for adding a document within an array that is nested within another document?

Apologies if the title seems complex... I struggled to find a better way to describe it. The scenario I am dealing with fits the following Schemes: Collection1: const mongoose = require('mongoose'); const itemSchema = mongoose.Schema({ _id: ...

What could be causing the error that pops up every time I attempt to execute a git push

When I executed the following command in git git push origin <the-name-of-my-branch> I encountered the following warning message Warning: The no-use-before-declare rule is deprecated since TypeScript 2.9. Please utilize the built-in compiler check ...

Executing npm prepublish on a complete project

I am facing a situation with some unconventional "local" npm modules that are written in TypeScript and have interdependencies like this: A -> B, C B -> C C -> D When I run npm install, it is crucial for all TypeScript compilation to happen in t ...

Is the ng-selector in Angular2 not sorting items alphabetically as expected?

This code snippet demonstrates the use of ng-selector in an .html file <ng-selector name="company" [(ngModel)]="company_selected" [formControl]="loanApplyForm.controls['company']" ...

Absent 'dist' folder in Aurelia VS2015 TypeScript project structure

After downloading the Aurelia VS2015 skeleton for typescript, I encountered an issue trying to run the Aurelia Navigation app in IIS Express. One modification that was made to the skeleton was adding "webroot": "wwwroot" to the top level of project.json. ...

Declare that a method alters a value with state

Here's a more streamlined version of my code. Check out my custom hook below: export const useStep = () => { const [step, setStep] = useState<Steps>("sending"); const changeStep = (newStep: Steps) => setStep(newStep); return { ste ...

Ways to determine the generic type of a property value from a decorated property within a decorator

While experimenting with some code, I encountered an issue where the generic type of a property value wasn't being resolved correctly when changing from TValue to (t: TValue) => TValue. Instead of being recognized as the expected number, it was now ...

The function 'appendChild' is not recognized on the type 'unknown'.ts(2339)

I'm encountering an issue while trying to integrate the Utterances component into my articles. Upon attempting to build the site, I receive the following error message: "Property 'appendChild' does not exist on type 'unknown' ...

Handling JSON data with Reactive Extensions in JavaScript

Hey everyone, I'm a beginner in Angular and RxJS coming from a background in VueJS. I've been struggling to grasp the inner workings of RxJS and would really benefit from some guidance from more experienced individuals regarding my current issue. ...

Issues with React Material UI Select functionality not performing as expected

I've been working on populating a Select Component from the Material UI library in React, but I'm facing an issue where I can't choose any of the options once they are populated. Below is my code snippet: import React, { useState, useEffect ...

ReferenceError: 'exports' is undefined in the context of Typescript Jest

I'm currently delving into unit testing with jest and encountered an error that looks like this: > npm run unit > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="771f181012374659475947">[email protected]</ ...

Struggling to configure Connected React Router correctly

As I work on updating my React, Redux, and Router versions to incorporate connected-react-router, I've encountered an issue with the root reducer and store creation process. The previous functioning reducer code looked like this: const appReducer = ...