"Developing with React Native just got easier with expo's vector-icons typescript type definition for specifying

Currently, I am in the process of determining the type definitions for the icon name within expo/vector-icons, as I have plans to utilize it for a component's props.

My approach involves importing expo/vector-icons and defining interface props by specifying the type of icon name as a string.

import Icon from "@expo/vector-icons/FontAwesome"

interface Props {
    icon: string
    value: string
    placeholder: string
    onChangeText: (text: string) => void
    secureTextEntry?: boolean
    style: StyleProp<ViewStyle>
}

This is how I am implementing the prop:

<Icon name={icon} size={20} style={styles.icon} />

Despite my efforts, Typescript presents me with an error. https://i.sstatic.net/L6H4v.jpg

Answer №1

To update the icon Props, you will need to modify its type,

import { Ionicons } from '@expo/vector-icons';

Then, utilize the glyphMap property from Ionicons in this manner

icon: keyof typeof Ionicons.glyphMap

Answer №2

To incorporate multiple Expo vector icons as properties in a custom component using Typescript, apply the steps below:

import { FontAwesome, MaterialIcons, Ionicons } from '@expo/vector-icons';


export enum IconType {
  MatetrialIcon,
  FontAweomseIcon,
  Ionicon,
}


type CustomProps = {
   icon: {
     value: { type: IconType.MatetrialIcon, name: keyof typeof MaterialIcons.glyphMap } |
            { type: IconType.FontAweomseIcon, name: keyof typeof FontAwesome.glyphMap } |
            { type: IconType.Ionicon, name: keyof typeof Ionicons.glyphMap };
     size: number;
   }
   
}


const CustomComponent = (props: CustomProps) => {
const { icon, ...otherProps } = props;

return 
  (
    <View style={styles.customIconStyle}>
      {icon.value.type === IconType.FontAweomseIcon && (
        <FontAwesome name={icon.value.name} size={icon.size} />
      )}
      {icon.value.type === IconType.MatetrialIcon && (
        <MaterialIcons name={icon.value.name} size={icon.size} />
      )}
      {icon.value.type === IconType.Ionicon && (
        <Ionicons name={icon.value.name} size={icon.size} />
      )}
    </View>
  );

}

Answer №3

To begin, start by importing the desired Icon from @expo/vertor-icons.

import Icon from "@expo/vector-icons/FontAwesome"

Next, make use of the glyphMap property in your type definition like so:

interface Props {
  icon: keyof typeof Icon.glyphMap
  value: string
  placeholder: string
  onChangeText: (text: string) => void
  secureTextEntry?: boolean
  style: StyleProp<ViewStyle>
}

Answer №4

import Icon from "@expo/vector-icons/MaterialCommunityIcons";
import { ComponentProps } from "react";

type Properties = ComponentProps<typeof Icon>;
export type IconIdentifier = Properties["name"];

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

Javascript operations for duplicating and altering arrays

In my Angular application, I am working with an array called subAgencies that is connected to a datasource. I need to implement 2-way binding on this array. Currently, I have a method in place where I copy the contents of the original array to a new one, ...

Can you explain the significance of the ampersand symbol (&) in a TypeScript type declaration?

Located at line 60359 of this specific type definition file, there is the following declaration: type ActivatedEventHandler = ( ev: Windows.ApplicationModel.Activation.IActivatedEventArgs & WinRTEvent<any> ) => void; How is the & ...

Encountering difficulties when attempting to load a module with the "js" extension in a TypeScript environment

When making a GET request with Systemjs, the extension .js is not being added to the URL. These are my TypeScript Classes customer.ts import {Address} from "./Address"; export class Customer { private _customerName: string = ""; public Customer ...

Tips for running Typescript files on a server in the background

I am currently working on a NodeJS application that consists solely of TypeScript files, without any JavaScript files. I'd like to run it on my server in the background. Any suggestions on how I can achieve this? I experimented with using the npm pa ...

What is causing the issue of URL parameters becoming undefined when performing service injection in the app component?

When working with a service that reads parameters from the URL, everything seems to be functioning properly until attempting to inject the service into the constructor of the app.component.ts file or trying to call a service method from the app.component.t ...

Using optional chaining on the left side in JavaScript is a convenient feature

Can the optional chaining operator be used on the left side of an assignment (=) in JavaScript? const building = {} building?.floor?.apartment?.number = 3; // Is this functionality supported? ...

Ways to retrieve form data from a dynamic CDKPortalComponent

I have a dynamic cdkportal component that is created from a variety of Components. These components are added to a modal dialog, and I need to determine the validity of the forms within them. If any of the child component forms are invalid, I want to disab ...

What is the best way to transform a synchronous function call into an observable?

Is there a conventional method or developer in RxJS 6 library that can transform a function call into an observable, as shown below? const liftFun = fun => { try { return of(fun()) } catch (err) { return throwError(err) } ...

Utilize NgRx's dispatch method to pass a payload and update the store

Exploring the world of ngRx is a new journey for me. I am currently in the process of establishing a store that will receive updates triggered by actions from components. NgRx create methods are being utilized to craft actions and reducers for this purpose ...

Is it possible for the <i></i> tag to be a self-closing tag in JSX?

I recently adhered to the Airbnb React/JSX style guide which mentions the importance of "Always self-closing tags that have no children". Does this rule apply to the <i></i> tag as well, considering it typically has no children? Would it be ac ...

Transmit information using express handlebars in a straightforward node application

Struggling to pass data from express handlebars to index.html? Check out my code below: server.js code: const express = require('express'); const app = express(); const expressHandlebars = require('express-handlebars'); const path = r ...

How to simulate a typescript class using vitest

I am encountering a situation where I have a class A that imports another class B from a separate module and creates an instance of it. While writing tests for class A, I want to stub or mock some of the methods of class B. Below is an example code snippe ...

Tips for sending a post request using Angular 4

I'm currently facing an issue while attempting to execute a post request using Angular 4 to transmit lat and lng parameters: let data = {lat: this.newLat, lng: this.newLng}; this.http.post(url, data) .map(response => response.json()) .subscri ...

ion-list with borders of different colors for each ion-avatar

I have a list of ion items, each displaying a round ion-avatar image with a colored border. Currently, I can only set one fixed color for all items. However, I would like each item to have a different color based on the value of listItem.color. Here is th ...

Error: React is not defined and cannot create an element

I've been working on transitioning a functional ReactJS application to TypeScript, but I've encountered some challenges getting everything to function correctly. import React from "react"; import * as ReactDOM from "react-dom"; import Applicatio ...

When working with the "agora-rtc-sdk-ng" package, an error may be thrown by Next.js stating that "window is not defined"

Currently, I am in the process of incorporating the "agora-rtc-sdk-ng" package for live streaming with next.js and typescript. import AgoraRTC from 'agora-rtc-sdk-ng'; However, when I try to import it, an error is thrown as shown below: https:/ ...

Is the treatment of an Observable distinct in Lambda compared to a Promise?

We have integrated the NestJS CQRS package into our application, which enables us to create 'sagas' through the generation of RxJS Observables that trigger various background tasks. An issue surfaced when deploying the application on AWS Lambda ...

Setting up Typescript with React 17 and Tailwind CSS version 2.0

I'm struggling to set up TailwindCSS 2.0 with the create-react-app --template typescript configuration and encountering errors. Even after following the instructions on the official TailwindCSS website for React at https://tailwindcss.com/docs/guides/ ...

TypeScript PatchBaseline with AWS CDK

I am currently working with the AWS CDK and TypeScript, utilizing the @aws-cdk/aws-ssm library to create a PatchBaseline. While I have successfully created the Patch baseline, I'm encountering difficulties when attempting to define approvalRules. I ca ...

Sign up for the completion event within the datetime picker feature in Ionic 2

How can I subscribe to the "done" event in Ionic2, where I want to trigger a function after selecting a date? <ion-icon class="moreicon" name="funnel"> <ion-datetime type="button" [(ngModel)]="myDate" (click)="getData()"></ion-datetime> ...