Generic Reusable Component React

Generic Reusable Component React

Generic types are use mainly to create reusable components with type-safety.

First, lets create a simple component first.

import React from 'react'

type TSelectOptions = { label: string, value: string }

type TSelectProps = { options: TSelectOptions[], onChange: (value: string)=> void }

export const Select = ({options, onChange}: SelectProps) => {
 return <select onChange={(e) => onChange(e)}> 
     {
         options.map((option)=> {
                <option key={option.value} value={option.value}>
                {option.label}
                </option>
         })
     }
 </select>
}

Now change this component into generic component.

type Base = {id: string, title: string} // Also added constraint 

type TSelectProps<TValue> = { values: TValue[], onChange: (value: TValue)=> void }

export const GenericSelect<TValue extends Base> = ({options, onChange}: TSelecteProps<TValue>) => {
 return <select onChange={(e) => onChange(e)}> 
     {
         values.map((value)=> {
                <option key={value.id} value={value.title}>
                {option.title}
                </option>
         })
     }
 </select>
}

So, this is how we create a reusable generic component.