React select options typescript

Create custom select component in React(Compound components pattern + Typescript)

Hai folks. In this blog we are going to build a custom select component using the compound components pattern. If you are not familiar with what are compound components pattern? and how does the compound components pattern looks like?. Please check out my blog on compound components. I hope you have used the native HTML Select Component. In the native select component, You can see there are two components : select and option. The both should be used in order to use the native select component.

select> option>Oneoption> option>Twooption> option>Threeoption> select> 
  • selectedOption (value of the currently selected option).
  • showDropdown (boolean value to show or hide the dropdown list).
import React,  ReactNode, useState, useRef > from "react"; import useOnClickOutside from "../../hooks/useOnClickOutside"; const Select: React.FC children: ReactNode | ReactNode[]; defaultValue?: string; placeholder?: string; >> = ( children, defaultValue, placeholder >) =>  const [selectedOption, setSelectedOption] = useState(defaultValue || ""); const [showDropdown, setShowDropdown] = useState(false); const showDropdownHandler = () => setShowDropdown(!showDropdown); const selectPlaceholder = placeholder || "Choose an option"; const clickOutsideHandler = () => setShowDropdown(false); // custom hook to detect the click on the outside useOnClickOutside(selectContainerRef, clickOutsideHandler); const updateSelectedOption = (option: string) =>  setSelectedOption(option); setShowDropdown(false); >; return ( div className="select-container" ref=selectContainerRef>> div className=showDropdown ? "selected-text active" : "selected-text"> onClick=showDropdownHandler> > selectedOption.length > 0 ? selectedOption : selectPlaceholder> div> ul className= showDropdown ? "select-options show-dropdown-options" : "select-options hide-dropdown-options" > > children> ul> div> ); >; export default Select; 

I am using a custom hook called useOnClickOutside. This hook is like a listener that accepts a ref and a callback function. the callback function will be called whenever the click event occurs outside the specified ref. I used this custom hook here to hide the dropdown list whenever the user clicks outside the select component. Now we had finished building the outer component (Select). Next step is to build the Option component.

import React,  ReactNode > from "react"; const Option: React.FC children: ReactNode | ReactNode[]; value: string; >> = ( children, value >) =>  return ( li className="select-option"> children> li> ); >; export default Option; 

The Option component is now built. Now the difficult part, We need to use the updateSelectedOption function which is present in the select component in the Option component. how are we going to share the function or state between Select and Option Components without passing through props?

Chill, React provides a way to share the data without passing through props, This is where the React Contexts comes into play. If you are not familiar with React context, please refer https://reactjs.org/docs/context.html.

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

Now Let’s write context for select component. We will be sharing two values : selectedOption & updateSelectedOption.

import  createContext, useContext > from "react"; const SelectContext = createContext selectedOption: string; changeSelectedOption: (option: string) => void; >>( selectedOption: "", changeSelectedOption: (option: string) => <> >); const useSelectContext = () =>  const context = useContext(SelectContext); if (!context)  throw new Error("Error in creating the context"); > return context; >; export  useSelectContext, SelectContext >; 

We had create the select context and useSelectContext is a custom hook for using the context. Now we need to provide the values to the context. We can provide values to the context using the SelectContext.Provider element.

// Select component SelectContext.Provider value= selectedOption, changeSelectedOption: updateSelectedOption >> > div className="select-container" ref=selectContainerRef>> . . div> SelectContext.Provider> 

Now we had provided the values to the Context. Next step is to use the provided values in the Option component. We can make use of useSelectContext to get the values from the context.

import React,  ReactNode > from "react"; import  useSelectContext > from "./selectContext"; const Option: React.FC children: ReactNode | ReactNode[]; value: string; >> = ( children, value >) =>  const  changeSelectedOption > = useSelectContext(); return ( li className="select-option" onClick=() => changeSelectedOption(value)>> children> li> ); >; export default Option; 

We had now connected the Option & Select component. Clicking on any of the option will trigger the changeSelectedOption function which will update the selectedOption state. We can also use selectedOption value in the context in the Option component for highlighting the selected option.

Select> Option value="one">OneOption> Option value="two">TwoOption> Option value="three">ThreeOption> Option value="four">FourOption> Select> 

Cheers folks. We had built the Select component which works the same way like the native select component.

You can get the complete code and check out the demo in the codesandbox. Happy coding friends.

Источник

Custom option render with react-select and Typescript

I have a react-select component in a Typescript project that looks like this (notice the component type annotations ♥️):

export type Category =  
label: string;
value: string;
>;

const categories = [ label: 'Option 1', value: '1' >, label: 'Option 2', value: '2' >]

SelectCategory>
classNamePrefix="my-prefix"
maxMenuHeight=200>
options=categories>
/>;

And I have to change it in order to show a description of each option:

custom options

Luckily enough, react-select is ultra customizable.

Option 1: using react-select components overrides ❌ #

First I thought I have to use a custom render. Something like this:

const OptionWithDescription = ( children, . props >) =>  
.
>;


Select
options=options>
components=
/>

But replacing components in react select is not a trivial task. Fortunately, there is a much simpler alternative.

Option 2: using formatOptionLabel ✅ #

This function recevies two parameters: the option itself (typed in the component) and some metadata. That metadata has the following type:

export interface FormatOptionLabelMetaOptionType extends OptionTypeBase>  
context: FormatOptionLabelContext;
inputValue: string;
selectValue: ValueTypeOptionType>;
>

export type FormatOptionLabelContext = "menu" | "value";

Add description to Cateogry #

The first to do is add an (optional) description to category:

export type Category =  
label: string;
value: string;
description?: string;
>;

Write a custom formatter #

We want to show the description only in menu:

function formatOptionLabel( 
category: Category,
meta: FormatOptionLabelMetaCategory>
)
const showDescription = meta.context === "menu" && category.description;

return showDescription ? (
div> div>category.label>div> div className=styles["form__select--description"]>> category.description> div> div>
) : (
div>category.label>div>
);
>
SelectCategory> 
.
formatOptionLabel=formatOptionLabel>
/>

Источник

React + TypeScript: Handling Select onChange Event

A select element is a drop-down list with multiple options. In this article, we will examine an end-to-end example of handling the onChange event of a select element in a React web app that written with TypeScript.

The Example

App Preview

What we are going to build is a simple web app that has a select element in the center of the screen. When a user chooses one option from the drop-down list, the selected value will be displayed.

The Complete Code

1. Create a new project with the command below:

npx create-react-app kindacode_example --template typescript

2. Replace all of the default code in your src/App.tsx (or src/App.ts) with the following:

// App.tsx // Kindacode.com import React, < useState >from "react"; const App = () => < const [selectedOption, setSelectedOption] = useState(); // This function is triggered when the select changes const selectChange = (event: React.ChangeEvent) => < const value = event.target.value; setSelectedOption(value); >; return ( 
> > >
); >; export default App; // Just some styles const styles: < [name: string]: React.CSSProperties >= < container: < marginTop: 50, display: "flex", flexDirection: "column", alignItems: "center", >, select: < padding: 5, width: 200, >, result: < marginTop: 30, >, >;

3. Run the project and go to http://localhost:3000 see the result:

Conclusion

You’ve learned how to handle the onChange event of a select element in React and TypeScript. If you would like to explore more new and interesting stuff about modern frontend development, take a look at the following articles:

You can also check our React category page and React Native category page for the latest tutorials and examples.

Источник

React select options typescript

  • Install npm i @types/react-select
  • Install npm i react-select
  • Good thing: It does search on complete word. If label is “microsoft” and user types “soft” then “microsoft” will be displayed in combo box.

datepicker

import < autobind >from '@uifabric/utilities'; import * as React from "react"; import Select from 'react-select'; import < ValueType >from 'react-select/lib/types'; interface IFlightsState < selectedFromPlace: ValueType>; > const options = [ < value: 'Typescript', label: 'Microsoft Typescript' >, < value: 'Angular', label: 'Angular Google' >, < value: 'React', label: 'React Facebook' >]; export class Flights extends React.Component  < constructor(props: any) < super(props); this.state = < selectedFromPlace: null, >> public render(): JSX.Element < return ( <> onChange= options= /> ); > @autobind private setSelectedFromPlace(selectedFromPlace: ValueType>): void < this.setState(< selectedFromPlace >); >; >

Share this:

Like this:

About siddarth

An average student from PSG College of Technology with an aim to become an omniscient in the field of technology.

Leave a Reply Cancel reply

Blog Stats

About Me

Top Posts & Pages

Recent Posts

  • Rate Limit Low Level Design Interview July 16, 2023
  • Atlassian Top K collections based on size May 1, 2023
  • async memoize May 1, 2023
  • Tree like file folder structure in react April 29, 2023
  • Solve third layer Rubik cube April 29, 2023
  • Implement async map limit | Uber frontend interview question February 14, 2023
  • A function that runs tasks with inter-dependency in JavaScript February 10, 2023
  • System design of 2 player online game February 1, 2023
  • Union Find Algorithm | Graph | The Earliest Moment When Everyone Become Friends January 24, 2023
  • Design Snake Game | JavaScript January 15, 2023

Categories

Оцените статью