Incorporating Moment.js into React Native Typescript for Enhanced Date and

I am currently facing an issue while using Moment.js and React Native to work with date and time. My code snippet below showcases how I am attempting to utilize the library.

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
import * as moment from 'moment';
import { Card } from 'react-native-paper';

interface event {
  title: string,
  created: any,
  expiration: any
}
const party : event = {
  title: '21st Bday Party',
  created: moment('2019 03 14'),
  expiration: moment('2019 03 15')
}

export default function App() {
  return (
    <View style={styles.container}>
      <Card>
        <Text>{party.created.format()}</Text>
      </Card>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
});

Upon running the code, I encounter the following error: TypeError: moment is not a function. Can someone please guide me on how to rectify this error?

Answer №1

The correct way to import moment is important.

Make sure you import moment in this format:

import moment from 'moment';

Remember to install the package before using it:

npm install moment --save

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

Leveraging es6-promise in conjunction with TypeScript 2.1 and ES5 Webpack for streamlined async/await functionality

Utilizing es6-promise with TypeScript version 2.1.1 that targets ES5 and webpack in my project has presented some challenges. app.ts import "es6-promise/auto"; export class Foo { bar() : Promise<string>{ return Promise.resolve("baz"); ...

Tips for retrieving Angular routing data from external sources outside of an Angular application

Is there a way to automatically generate a sitemap for each module during build time? The project structure is as follows: - cli - client -- Module A -- Routing A -- Module B -- Routing B -- Module C -- Routing C - server I am ...

What steps can be taken when encountering TS errors regarding missing required fields that are in the process of being filled?

In a typical scenario, the process involves creating an empty object and populating it with the necessary data. Initially, this object does not contain any properties, which leads to TypeScript flagging an error since it lacks the required type. For insta ...

Resolving issues with Typescript declarations for React Component

Currently utilizing React 16.4.1 and Typescript 2.9.2, I am attempting to use the reaptcha library from here. The library is imported like so: import * as Reaptcha from 'reaptcha'; Since there are no type definitions provided, building results ...

The type 'IProduct' cannot be assigned to type '[]'

Looking for help with dispatching events between parent and child components. Interfaces: export interface IProduct { id: string; name: string; price: string; image: string; inStock: number; fastDelivery: bo ...

Starting up a pre-existing Angular project on your local machine

I am completely new to Angular and facing difficulties running an existing project on my machine. Despite conducting numerous tests and following various articles, I still cannot get the project to run. Here is the layout of my project files: https://i.s ...

The Jest type definitions seem to be malfunctioning in this TypeScript project

Recently, I began a new Typescript project utilizing GTS. While the typings are functioning correctly for regular *.ts files, I am encountering difficulties in getting *.spec.ts files to work. Issue Each jest function is being flagged as red by ESLint wit ...

Obtain a union type in TypeScript based on the values of a field within another union type

Is it feasible in Typescript to derive a union type from the values of a field within another union type? type MyUnionType = | { foo: 'a', bar: 1 } | { foo: 'b', bar: 2 } | { foo: 'c', bar: 3 } // Is there an automati ...

Tips for preventing a promise from being executed more than once within an observable while being subscribed to a BehaviorSubject

I've defined a class called Store with the following structure: import { BehaviorSubject, Observable } from 'rxjs' export abstract class Store<T> { private state: BehaviorSubject<T> = new BehaviorSubject((undefined as unknown ...

Is there a possibility in TypeScript to indicate "as well as any additional ones"?

When working with typescript, it's important to define the variable type. Consider this example: userData: {id: number, name: string}; But what if you want to allow other keys with any types that won't be validated? Is there a way to achieve thi ...

Why aren't special methods/mixins for Sequelize associations being generated?

According to the documentation available at https://sequelize.org/docs/v6/core-concepts/assocs/#special-methodsmixins-added-to-instances: When establishing an association between two models, special methods are introduced that enable instances of those mo ...

The issue of TypeScript failing to return HTML Template Element from Constructor typing is causing complications

There is a restriction on using new to create an instance of Template, which extends an HTMLTemplateElement. To work around this limitation, I fetch and return an HTMLTemplateElement by using document.getElementById(id) within the constructor of the Templ ...

Issue: The module is not compatible with the "node" engine. It requires version ">= 14.20.0" but is receiving "14.17.4"

In the midst of working on a challenging branch, I struggled to organize my dependencies. However, after lots of effort, I finally managed to get everything up and running smoothly, with my GitLab pipelines passing successfully. Just so you know, the proje ...

How to automatically scroll to the most recently added element in an *ngFor loop using Angular 2

In my web page, I have a dynamic list rendered using an ngFor loop. Users can add or remove elements from this list by clicking on a button. What I want to achieve is to automatically scroll the browser view to the latest element added when a user clicks o ...

Managing Observable<Person[]> in ng-bootstrap typeahead instead of Observable<string[]>: a complete guide

I'm new to Angular/Typescript and have a question. I recently tried out the example from Wikipedia in ng-bootstrap typeahead. Instead of using the Wikipedia call, I decided to use a custom REST service that has the following GET endpoint: GET /pers ...

Converting React to Typescript and refactoring it leads to an issue where the property 'readOnly' is not recognized on the type 'IntrinsicAttributes & InputProps & { children?: ReactNode; }'

I'm currently in the process of refactoring an application using Typescript. Everything is going smoothly except for one particular component. I am utilizing the Input component from the library material-ui. import {Input} from "material-ui"; class ...

Property '{}' is not defined in type - Angular version 9.1.1

Currently, I am working with Angular CLI version 9.1.1 and I am attempting to update certain data without updating all of it. form: UserInfo = {adresse : {}}; UserInfo.interface export interface UserInfo { id_user: string; username: string; em ...

Looking for assistance in setting up a straightforward TypeScript Preact application

I recently started exploring preact and I'm attempting to create a basic app using typescript in preact. I've noticed that their default and typescript templates include extras like jest and testing, which I don't necessarily require. Althou ...

Using TypeORM to Retrieve Data from Many-to-Many Relationships with Special Attributes

Hey there, I'm diving into the world of TypeORM and could really use some guidance. I've been attempting to set up many-to-many relationships with custom properties following the instructions provided here However, I've run into a few iss ...

Tips on utilizing the identical template in ngIf

I need to display different templates based on certain conditions. For example: <template [ngIf]="item.url.indexOf('http') == -1"> <a class="ripple-effect" [routerLink]="[item.url]" *ngIf="isUserLoggedIn == true" > ...