Reputation: 313
Hi i didn't understand why my onclick function didn't work. my function create run herself 2 time at the loading of the page but not when i click on the button
import React, { Component, PropTypes } from 'react';
import { createContainer } from 'meteor/react-meteor-data';
import { Topics } from '../api/topic.js';
import Topic from './Topic.jsx';
class AppCreate extends Component {
render(){
return(
<div className="container">
<form>
<input type="text" placeholder="donnez un nom a votre Topic" className="topic"></input>
<input type="button" value="Créer" onClick={this.create()}></input>
</form>
</div>
);
}
create(e){
{var test = document.getElementsByClassName("topic").value;
console.log(test);}
}
}
AppCreate.propTypes = {
topics: PropTypes.array.isRequired
};
export default createContainer(() => {
return {
topics: Topics.find({}).fetch(),
};
}, AppCreate);
Upvotes: 1
Views: 1496
Reputation: 55448
Why it doesn't work
When you're passing onClick={this.create()}
you're actually passing the return value of the function, and not the function it self. As a side effect, this will also cause that function to be called when a render occurs, not only when a user actually clicks.
Solution
You want to pass the function itself to be called, notice there are no parentheses ()
:
onClick={this.create}
If you need to access the component instance in the click handle
You'll also want to bind this
(the instance of your component) inside your method, e.g. to access this.state
you'll have to bind that value
onClick={this.create.bind(this)}
With this the execution inside create() will have a this
value equal to the instance of your component, allowing you to access its attributes and methods like this.props
, this.state
and other methods you have defined on the component.
Upvotes: 3