0

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

3
  • 1
    Possible duplicate of onClick not working React js Commented May 8, 2019 at 17:43
  • I've looked at that and it hasn't halped me Commented May 8, 2019 at 17:46
  • 1
    I've been clicking the wrong button, I don't know how long for Commented May 8, 2019 at 18:17

2 Answers 2

1

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

  ClearNewNote = (e) => {
    e.target.style.backgroundColor = '#ccc';
  };
Sign up to request clarification or add additional context in comments.

3 Comments

no change I'm afraid. Have tried it before and after the class, inside and out
did you tried binding the ClearNewNote method in constructor and the using it ?
try now.. its changing the color of save button to #ccc
1

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);

1 Comment

This works but I can't see the differences between that and my code

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.