0

I'm trying to make a simple message app that takes the users name, and a message, then the messages are passed down and displayed in another component. In the component that should display the messages I'm getting an error saying this.props.messages.map is not a function.

Here is my code sandbox:

https://codesandbox.io/s/unruffled-pasteur-nz32o

And here is my actual code:

Parent component:

import React, { Component } from "react";
import Messages from "./Messages";
import Input from "./Input";

export default class Container extends Component {
  constructor(props) {
    super(props);
    this.state = {
      messages: {
        user: [],
        message: []
      }
    };
  }

  updateMessage(message, sender) {
    this.setState({
      messages: [...this.state.messages, { user: sender, message: message }]
    });
  }

  render() {
    return (
      <div>
        <Messages messages={this.state.messages} />
        <Input
            updateMessage={(message, sender) =>
            this.updateMessage(message, sender)
          }
        />
      </div>
    );
  }
}

And here is where the messages should be displayed (and also where I am getting the error):

import React, { Component } from "react";

export default class Messages extends Component {
  render() {
    return this.props.messages.map(message => {
      return (
        <div>
          {message.user}: {message.maessage}
        </div>
     );
    });
  }
}

Any ideas what could be causing my error? Thanks!

1 Answer 1

1

messages is initialized as an object in state. If you want to map over it, it should be an array. So rather than this:

  constructor(props) {
    super(props);
    this.state = {
      messages: {
        user: [],
        message: []
      }
    };
  }

You'll, want this:

  constructor(props) {
    super(props);

    this.state = {
      messages: [
        {
          user: [],
          message: []
        }
      ]
    };
  }
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, that makes sense. I'll give you the checkmark after the time limit runs up. Thanks!
@Djaenike heads up in your message component you also have a typo: {message.maessage} should be {message.message}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.