Reputation: 2319
I have an input field that's freetext form. I want to take this value and click a "submit" button to make a POST request.
It's as simple as
<input className="inputbox" type="text" name="Email" placeholder="Enter email..." onChange={event => this.handleInputOnChange(event)}/>
<button type="submit" className={confirmClass} onClick={this.props.handleConfirm(this.state.email)} disabled={!this.state.email}>Confirm</button>
Where handleInputOnChange
is
handleInputOnChange(event) {
this.setState({"email": event.target.value});
}
and handleConfirm
is
handleConfirm = (email) => {
http.post(someUrl + '/somefunc/',
{"some_email": email})
.then((result) => {this.setState({"some_email": email})});
window.location.reload();
}
http.post
is a custom request function that has some additional headers in it.
But now when I load the page, it goes into an infinite loop. It actually doesn't have any error message. Just keeps looping nonstop.
What's the cause of this and how do I make a POST call with what's in the input?
Upvotes: 0
Views: 43
Reputation: 1941
If you write onClick={() => this.props.handleConfirm(this.state.email)}
the event would be assigned a function that executed on the event. If you write onClick={this.props.handleConfirm(this.state.email)}
it will be executed on the component render.
As far as I understand react and jsx every js code within the jsx would be executed. This way you get for example <div style={{ opacity: this.state.loading ? 0.5 : 1}}>...</div>
to generate the expected div with opacity or without because the statement this.state.loading ? 0.5 : 1
is evaluated and you see the result. Same thing when you write in your js code myFunc()
js will call this function. So if you want to assign onClick to a function instead of calling a function you need to assign it to an anonymous function () => {}
or in you case () => this.props.handle()
you are assigning an anonymous function that will call another function.
Last point to the topic, if you just want to reference an existing function you can write onClick={this.eventHandler}
and it should also work as expected.
Upvotes: 1