Search code examples
javascriptreact-nativereact-functional-componentreact-native-gifted-chatreact-class-based-component

React Native: Functional Component to Class Component


I am using React Native Gifted Code.

I am trying to convert the following example to class component: example image

And here's is my code snippet provided below:

constructor(props) {
    super(props);
    this.state = {
        message: [{
            _id: 1,
            text: 'Hello developer',
            createdAt: new Date(),
            user: {
                _id: 2,
                name: 'React Native',
                avatar: 'https://placeimg.com/140/140/any',
            },
        }],
    }
}

componentDidMount() { }

onSend(messageSend = []) {
    this.setState(
        previousMessages => ({
            message: GiftedChat.append(previousMessages, messageSend)
        })
    );
}

render() {
    const chat = <GiftedChat
        messages={this.state.message}
        onSend={(messageSend) => this.onSend(messageSend)}
        user={{
            _id: 1,
        }}
    />;

    if (Platform.OS === 'android') {
        return (
            <KeyboardAvoidingView
                style={{ flex: 1 }}
                behaviour="padding"
                keyboardVerticalOffset={30}
                enabled
            >
                {chat}
            </KeyboardAvoidingView>
        );
    }
}

However, after converting to class component I am not the getting the desired outcome. (something similar to this)

The issue is when sending a new message, it's 'replacing' the sender's message with my latest message.


Solution

  • Apparently I had to add previousMessages.messsage instead of previousMessages.

    SOLUTION:

    //send message will no longer overlap/replace 'hello developer'
            onSend(messageSend = []) {
            this.setState(
                previousMessages => ({
                    message: GiftedChat.append(previousMessages.messsage, messageSend)
                })
            );
        }