ReactJS - Cannot read property 'preventDefault' of undefined

Reena Verma picture Reena Verma · Jun 23, 2018 · Viewed 13.5k times · Source

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.

Answer

Sashini Hettiarachchi picture Sashini Hettiarachchi · Nov 3, 2018

You should bind this event to "handleClick()" function. As follows,

<GiphyButton onClick={this.handleClick.bind(this)}/>