Reputation: 73
I have his code where i try to pass a variable to the handleclick fcn and set state to that variable:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'Initial State'
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(temp) {
this.setState({
name:temp
});
}
render() {
return (
<div>
<button onClick={this.handleClick('name')}>Click Me</button>
<h1>{this.state.name}</h1>
</div>
);
}
};
It doesn't work, can someone explain how to pass a variable and set state to it, if it's possible??
Upvotes: 0
Views: 55
Reputation: 112787
By writing this.handleClick('name')
you are invoking the handleClick
function directly on render. You want to give a function to the onClick
prop that will be invoked on click.
Example
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "Initial State"
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(temp) {
this.setState({
name: temp
});
}
render() {
return (
<div>
<button onClick={() => this.handleClick("name")}>Click Me</button>
<h1>{this.state.name}</h1>
</div>
);
}
}
ReactDOM.render(<MyComponent />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Upvotes: 2