Reputation: 1865
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!
Upvotes: 0
Views: 63
Reputation: 5650
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: []
}
]
};
}
Upvotes: 1