Vikramaditya
Vikramaditya

Reputation: 5574

onClick event not triggering reactjs

<!DOCTYPE html>
<html>
<style>
  ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
  }
  li {
    display: inline;
  }
  #outer {
    margin-left: 20%;
  }
  #icon {
    display: inline;
  }
</style>

<head lang="en">
  <meta charset="UTF-8">
  <title>React Image Slider</title>
  <script src="https://fb.me/react-0.13.1.js"></script>
  <script src="https://fb.me/JSXTransformer-0.13.1.js"></script>
</head>

<body>
  <script type="text/jsx">
    var Slider = React.createClass({ changeImage: function(e){ console.log("i m here"); }, render: function () { var lib = this.props.imageData; return
    <div>
      <div id="outer">
        <img src="http://placehold.it/300x300" width="300" height="300" />
      </div>
      <ul>
        {lib.map(function(l){ return
        <li>
          <div id="icon">
            <input type="image" onClick={ this.changeImage} src={l.icon} alt="Submit" width="100" height="100" /> <span>{l.name}</span>
          </div>
        </li>
        }) }
      </ul>
    </div>; } } ); 
var arr_img = [ { name: 'Image1', url: 'http://placehold.it/940x528', icon: 'http://placehold.it/100x100'}, { name: 'Image2', url: 'http://placehold.it/940x528', icon: 'http://placehold.it/100x100'}, { name: 'Image3', url: 'http://placehold.it/940x528',
    icon: 'http://placehold.it/100x100'}, { name: 'Image4', url: 'http://placehold.it/940x528', icon: 'http://placehold.it/100x100'}, { name: 'Image5', url: 'http://placehold.it/940x528', icon: 'http://placehold.it/100x100'}, { name: 'Image6', url: 'http://placehold.it/940x528',
    icon: 'http://placehold.it/100x100'}, { name: 'Image7', url: 'http://placehold.it/940x528', icon: 'http://placehold.it/100x100'}, { name: 'Image8', url: 'http://placehold.it/940x528', icon: 'http://placehold.it/100x100'} ]; 
React.render(
    <Slider imageData={ arr_img} />, document.body );

  </script>
</body>

</html>

Upvotes: 0

Views: 242

Answers (1)

Colin Ramsay
Colin Ramsay

Reputation: 16466

The problem is that this.changeImage will be undefined when you pass it in, because you need to set the scope of the function you're passing to map:

// Add `this` as a second parameter
lib.map(function(l){ }, this);

I should say that this has nothing to do with React and everything to do with plain, simple JavaScript.

Upvotes: 3

Related Questions