Search code examples
javascriptreact-nativereact-native-gifted-chat

Getting error when I import 'dayjs/local/en'?


I want to add locale to my react-native-gifted-chat, because the chats do not show up one after the other, I am guessing because of time zones.

I added Locale to my gifted chat:

 import en from 'dayjs/locale/en'

 render() { 
    return (
        <View style={{backgroundColor: '#000000', flex: 1}}>
            <GiftedChat
                showUserAvatar={true}
                isTyping={this.state.isTyping}
                renderUsernameOnMessage={true}
                messages={this.state.messages}
                onSend={message => this.onSend(message)}
                scrollToBottom
                locale = { en } <-----------------------------
                showAvatarForEveryMessage = {false}
                showUserAvatar= {true}
                dateFormat = 'll'
                timeFormat = 'LT'
                placeholder = "Talk to people..."
                onPressAvatar={user => this.getProfile(user)}
            />
        </View>
        
    )

But now I get the error:

TypeError: undefined is not an object (evaluating 'n[M].replace')

Is this because I am using the wrong type of import, or is the existing chats the issue, and do I need to delete them for things to work?


Solution

  • Looking at the documentation, it appears you need to import the locale file separately.

    First you need to import daysjs:

    import dayjs from 'dayjs';
    

    Then you need to import the locale you want:

    import 'dayjs/locale/en'
    

    This appears to have a global mutation side effect (bad) of making that locale available for formatting.

    In your prop, pass in locale="en"

    Then in your component (if you own it) you can use dayjs(date).locale(this.props.locale).format()

    Daysjs doesn't look like a well designed library, because imports shouldn't have side effects like this.