My onClick isn't firing on click, but rather when the page loads. Here's the relevant code:
App.js
callAPI(x) {
fetch("http://localhost:8080/" + x)
.then(res => res.text())
.then(res => this.setState({ apiResponse: res }))
.catch(err => err);
}
render() {
<Button
onClick={this.callAPI('api')}
type="success"
className="input-lg">
Search
</Button>
Button ponent:
import React from "react";
function Button({ type = "default", className, children, onClick }) {
return (
<button onClick={onClick} className={["btn btn-lg", `btn-${type}`,
className].join(" ")}>
{children}
</button>
);
}
export default Button;
Any help is greatly appreciated!
My onClick isn't firing on click, but rather when the page loads. Here's the relevant code:
App.js
callAPI(x) {
fetch("http://localhost:8080/" + x)
.then(res => res.text())
.then(res => this.setState({ apiResponse: res }))
.catch(err => err);
}
render() {
<Button
onClick={this.callAPI('api')}
type="success"
className="input-lg">
Search
</Button>
Button ponent:
import React from "react";
function Button({ type = "default", className, children, onClick }) {
return (
<button onClick={onClick} className={["btn btn-lg", `btn-${type}`,
className].join(" ")}>
{children}
</button>
);
}
export default Button;
Any help is greatly appreciated!
Share Improve this question asked Apr 1, 2019 at 17:24 wangdoodlewangdoodle 312 silver badges7 bronze badges 1- Hi Andy, could you accept one of the answers to close the question? – Dupocas Commented Apr 1, 2019 at 19:23
3 Answers
Reset to default 3Change
<Button onClick={this.callAPI('api')} type="success" className="input-lg">
Search
</Button>
to
<Button onClick={() => this.callAPI('api')} type="success" className="input-lg">
Search
</Button>
You are calling the function as soon as the prop is set instead of when it is clicked. To get the function to fire when clicked you need to pass in a function that has not been called.
It's becouse you use fire it up automatically. Try something like this.
<Button
onClick={() => this.callAPI('api')}
type="success"
className="input-lg">
Search
</Button>
<script src="https://cdnjs.cloudflare./ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Change
onClick={this.callAPI('api')}
To
onClick={() => this.callAPI('api')}