Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS - Cannot read property 'preventDefault' of undefined

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.

like image 731
Reena Verma Avatar asked Jun 23 '18 20:06

Reena Verma


1 Answers

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

<GiphyButton onClick={this.handleClick.bind(this)}/>
like image 93
Sashini Hettiarachchi Avatar answered Oct 18 '22 19:10

Sashini Hettiarachchi