Trying to do a simple onClick event/function, in ReactJS.
When the button is clicked, I want to run a function called "onClick", but I get this error in console:
app.js:62 Uncaught TypeError: Cannot read property 'preventDefault' of undefined
Have googled, but not sure what I'm going wrong. I've looked at ReactJs documentation and this looks correct, but obviously not. Here's my code:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter} from 'react-router-dom';
import axios from 'axios';
import Navbar from './components/Navbar';
import Header from './components/Header';
import GiphyButton from './components/GiphyButton';
import './assets/sass/main.scss';
class App extends React.Component {
constructor() {
super();
this.state = {
giphy: []
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
e.preventDefault();
console.log('giffy button clicked');
axios.get('http://api.giphy.com/v1/gifs/search?q=otters&api_key=<API KEY>')
.then(res => {
this.setState({ giphy: res.data });
console.log(res.data);
});
}
render() {
return (
<BrowserRouter>
<main>
<Navbar />
<Header />
<GiphyButton onClick={this.handleClick()}/>
</main>
</BrowserRouter>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
GiphyButton is a component, which is literally, just JSX for a . No other functions running here:
import React from 'react';
const GiphyButton = () => (
<section>
<button>See more otters</button>
</section>
);
export default GiphyButton;
Thank you.
You should bind this event to "handleClick()" function. As follows,
<GiphyButton onClick={this.handleClick.bind(this)}/>
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