Luke Pring
Luke Pring

Reputation: 992

React onclick listener

So I've created and followed several tutorials but I still can't get the onClick listener to work. Can anyone Advise, please?

I have tried to implement the given example (based my code off of that and similar) and the onClick function is not being called. I have also tried onClick={function(e){console.log('clicked')}} with no response from the console

import React, {Component} from 'react';
import './App.css';

class App extends Component {
  ClearNewNote = (e) => {
    e.target.style.backgroundColor = '#ccc';
  };
  render() {
    return(
      <div className="App">
        <header className="App-header">
          <h1>Simple Note Pad</h1>
        </header>
        <main>
          <div className="CreateNewNote">
            <div className="Controls">
              <button className="ClearNewNote">Clear</button>
              <button className="SaveNewNote" onClick={this.ClearNewNote.bind(this)}>Save</button>
            </div>
            <div className="NewNoteInput">
              <textarea></textarea>
            </div>
          </div>
        </main>
      </div>
    );
  };
}

export default App;

EDITS: Updated to in align with suggestions, no error codes and no changes when click

Upvotes: 0

Views: 298

Answers (2)

orvi
orvi

Reputation: 3340

Check this one

import React, { Component } from "react";
import ReactDOM from "react-dom";

class App extends Component {
  ClearNewNote(e) {
    e.currentTarget.style.backgroundColor = "red";
  }

  render() {
    return (
      <div>
        <button onClick={this.ClearNewNote}>Click on me</button>
      </div>
    );
  }
}

export default App;

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Upvotes: 1

Murtaza Hussain
Murtaza Hussain

Reputation: 4285

use arrow functions to use the this context fo the Component. and change currentTarget to target;

  ClearNewNote = (e) => {
    e.target.style.backgroundColor = '#ccc';
  };

Upvotes: 1

Related Questions