Playing with react, trying to build a simple chat app that will be connected to firebase.
I have one container - ChatApp - and one component UserInput.
ChatApp ->
import React from 'react';
import UserInput from '../components/UserInput';
export default React.createClass({
getInitialState: function() {
return {
chatting: false
};
},
render: function() {
return <div>
<UserInput
startChat={this.chatCanStart}
/>
</div>;
},
chatCanStart: function(recipient) {
console.log(recipient);
this.setState({
chatting: true
})
}
});
UserInput ->
import React from 'react';
export default React.createClass({
getInitialState: function() {
return {
username: '',
recipient: 'asgasg'
};
},
handleUsernameChange: function(event) {
let text = event.target.text;
this.setState({
username: text
});
},
handleRecipientChange: function(event) {
let text = event.target.text;
this.setState({
recipient: text
});
},
handleStartChat: function() {
if (this.state.username !== '' && this.state.recipient !== ''){
console.log(this.state.recipient);
this.props.startChat(this.state.recipient);
}
},
render: function() {
return <div className="panel panel-default">
<div className="panel-heading"> Welcome to the chat app done in React </div>
<div className="panel-body">
<div className="input-group">
<span className="input-group-addon"> Username </span>
<input type="email" className="form-control" value={this.state.username} onChange={this.handleUsernameChange} />
</div>
<br />
<div className="input-group">
<span className="input-group-addon"> Recipient </span>
<input type="email" className="form-control" value={this.state.recipient} onChange={this.handleRecipientChange} />
</div>
<br />
<button type="button" className="btn btn-primary" onClick={this.handleStartChat}> Chat now </button>
</div>
</div>;
}
});
When I change the Username and Recipient fields and then click on the Chat now button, I am expecting the chatting state in the ChatApp container to change to true and also want to log the passed recipient.
But I get 'undefined', why is that? I get 'undefined' even in the console.log in the UserInput component. Even though the inputs value in the form is being changed just fine.
What am I doing wrong?
Thanks.
To get value from input you need to use .value property instead of .text
handleUsernameChange: function(event) {
let text = event.target.value;
this.setState({
username: text
});
},
handleRecipientChange: function(event) {
let text = event.target.value;
this.setState({
recipient: text
});
},
Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With