Mewshinyex
Mewshinyex

Reputation: 27

onClick this returning undefined in React

I first want to apologize for my poor level in React, I am an absolute beginner in this framework.

I am trying to trigger a simple function when a rendered element is clicked.

I want that, on click, this element's background property turns to blue.

I know that, in regular ES6, achieving this is quite simple. However, none of my trials have succeeded in React. I am then asking for your precious help here!

Here's my code :

import React, { Component } from 'react';
import logo from './images/stellar.png';

function openMenu(machin){
  console.log(machin);
  machin.props.style.backgroundColor = 'blue';
}

class App extends Component {

  render() {

    return (

      <div id="background">
        <div className="navbar">
            <div className="imgContainer" onClick={()=>{ openMenu(this) }}>
              <img src={logo} alt="logo" />
            </div>
            <b>About</b>
        </div>
      </div>

    );

  }

}

export default App;

The most relevant alternative trial I've done is the following :

<div className="imgContainer" onClick={openMenu(this)}>
// Triggered function below ↓
function openMenu(){
  console.log(this);
  this.props.style.backgroundColor = 'blue';
}

I also tried bypassing props in my code (like this.style.backgroundColor directly), with no significant result.

As of now, the error message is the following : Error Image

Any help is really appreciated!

Many thanks in advance

Upvotes: 1

Views: 529

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

While you could "fix" it by using the event from the click handler to get to the clicked element:

<div className="imgContainer" onClick={(e)=>{ openMenu(e.target) }}>

That's not the proper React way of doing things. Put the status of whether the menu is opened or not into state instead, and change state instead of using DOM methods:

const logo = 'https://www.gravatar.com/avatar/65f22377d41ecf71a89602c73d4d9889?s=32&d=identicon&r=PG&f=1';
const App = () => {
  const [open, setOpen] = React.useState(false);
  return (
    <div id="background" className={open ? 'open' : ''}>
      <div className="navbar">
          <div className="imgContainer" onClick={()=>{ setOpen(!open) }}>
            <img src={logo} alt="logo" />
          </div>
          <b>About</b>
      </div>
    </div>

  );
};
ReactDOM.render(<App />, document.querySelector('.react'));
.open {
  background-color: blue;
}
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class="react"></div>

(put the className={open ? 'open' : ''} into whatever element needs to have its background color changed)

Upvotes: 2

Related Questions