I'm new to react, have created a chat using reactjs. I'm using "POST" request through fetch to post new message for a particular conversation. My Objective is when i send a message, then it should clear the input but unable to clear the input after sending message. Anyone can help me in this?
Asked
Active
Viewed 76 times
3 Answers
0
You'd need to read value
in your Input
from the state, and then reset the state after sending the request:
handleChange = event => {
this.setState({ [event.target.name]: event.target.value });
};
handleSend = event => {
const { phonNo } = this.props.phonNo;
event.preventDefault();
console.log("phone : " + "+" + phonNo);
this.setState({ toPhoneno: phonNo });
console.log("phonefkjdk : " + "+" + this.state.toPhoneno);
const data = {
toPhoneNumber: "+" + this.state.toPhoneno,
body: this.state.body
};
fetch("/api/messages", {
method: "POST",
body: JSON.stringify(data),
headers: { "Content-Type": "application/json" }
})
.then(res => res.json())
.then(() => {
this.setState({body: ''}); // reset input value
});
};
render () {
return (
<div>
<input
className="sendMessage"
onChange={this.handleChange}
id="body"
name="body"
value={this.state.body || ''} //read value from the state
/>
<Button onClick={this.handleSend} className="sendBtn" icon>
<Icon name="send" color="blue" />
</Button>
</div>
);
}

Clarity
- 10,730
- 2
- 25
- 35
-
I'm getting error as "Unhandled Rejection (SyntaxError): Unexpected end of JSON input" What to do? – Chandan Nov 26 '19 at 02:59
-
Can't see what's wrong without seeing the code, which you removed from the question. – Clarity Nov 27 '19 at 09:50
-
I've updated the link, Could you please check it once – Chandan Nov 27 '19 at 10:39
-
Can you please check the above link, I've updated in my query. – Chandan Nov 27 '19 at 10:57
0
Here instead of using the controlled inputs, you can use the uncontrolled inputs also as there is no need to re-render the component on each value entered.
Controlled vs Uncontrolled Inputs
Following the above link, once you are done sending the message, you can easily clear the input as
this.input.value = ''
Controlled inputs are mostly used when you need to update the state immediately when u type. I feel you might not need it here.

Vishal Sharma
- 316
- 1
- 8
-1
You can use simple Javascript for this.
After your API response, type this where you want the input box to be cleared.
document.getElementById('myInput').value = '';
UPDATE:
Use ReactDOM to change the value as follows:
<input type="text" ref="input" />
ReactDOM.findDOMNode(this.refs.input).value = '';

PiNaKa30
- 608
- 7
- 20
-
-
It's better to do it via state manipulation than using refs in a jQuery style way. – Clarity Nov 22 '19 at 10:51