1

I followed a tutorial to use react-select dropdown in my react js , typscript project. I was able to work with the code below, but I am new to react js and typescript. how do i get the value of the selected in the code below. say, in the selectHandler function , i want to compare selected value as such

`
  if ( this.state.someValue == 'b") 
`

I get an error because, this.state.someValue is not a string . how to extract the just the value after user selects it.

import * as React from "react";
import Select, {ValueType} from 'react-select';
 
interface SomeState { someValue: ValueType<{ value: string; label: string; }>; }
 
const opt = [{ value: 'a', label: 'awesome' }, { value: 'b', label: 'boring' }];
 
export class someClass extends React.Component<any, SomeState> {
 constructor(props: any) {
   super(props);
   this.state = { someValue: null}
 }
 
 public render(): JSX.Element {
  return ( <>
    <Select value={this.state.someValue} onChange={this.selectHandler} options={opt} />
  </> );}

 private selectHandler (selectedFromPlace: ValueType<{ value: string; label: string; }>): 
  void {
        this.setState({ someValue});
    };
}`
2
  • 1
    Which version of react-select are you using? Commented May 26, 2021 at 0:59
  • version 16.13.1 Commented May 26, 2021 at 2:36

1 Answer 1

1

Your value is of type object with the keys label and value . To extract only the value from your selected option .

In your select handler you are getting the selected option in the name selectedFromPlace .

So to get only the value you need to do selectedFromPlace.value

Sign up to request clarification or add additional context in comments.

3 Comments

nope , still not working , when I try selectedFromPlace?.value, i get error Property 'value' does not exist on type '{value : string; label: string;} | OptionsType<{value: string; label:string}>
my guess is , i will have to cast that object to to type of OptionsType , may be
where are you trying to access the value ? . It seems to work for me . Here is the sandbox - codesandbox.io/s/quirky-frog-1wp26?file=/src/App.tsx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.