Skip to content
Advertisement

Error using new Date() in react Native is not a constructor

When I use new Date(); in react native to create a new date or time I get the error:

TypeError: undefined is not a constructor (evaluating ‘new _reactNative.Date()’)

What could be causing this? Is there something I am not importing into react Native?

import React from 'react';

import { StyleSheet, View, Text, Button, Image, TouchableOpacity, Date, ScrollView } from 'react-native';


export default class AddAProfile extends React.Component {


const date = new Date();

render () {

return (
   <View>
    {this.date}
   </View>


)

}}

export default AddAProfile;

Advertisement

Answer

There are several issues here that are fogging things up. First of all, classes in React should have a constructor, and if you’re going to use class parameters, the constructor needs a call to super(). Second of all, there isn’t a View component in the class, so create one or use elements instead. Thirdly, in order to display the date, you will need to chain a toString() at the end.

See the code below.

class AddAProfile extends React.Component {
    constructor() {
        super();
        this.d = new Date().toString();
    }
    
    render() {
        return(
        <p>{this.d}</p>
        )
    }
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement