Reputation: 153
I started play with React and I'm stuck with this sample.
Counter works but why onClick the BUTTON does not change key active in state and render correct button?
Link to CodePen
const Button = ({label}) => (
<button className="btn btn-primary">{label}</button>
);
const Counter = React.createClass({
getInitialState: function () {
return {
counter: 0,
active: false
}
},
increment: function () {
this.setState({
counter: this.state.counter + 1
})
},
change: function () {
this.setState({
active: true
})
},
render: function () {
return (
<div>
<h1>Counter: {this.state.counter}</h1>
<button onClick={this.increment}>1+</button>}
{this.state.active ?
<Button label="Sign OUT"/> :
<Button label="Sign in" onClick={this.change}/>}
</div>
)
}
});
ReactDOM.render(<Counter/>, document.getElementById("root"))
Upvotes: 2
Views: 2546
Reputation: 104369
Because you forgot to define click
event in Button
Component use this:
const Button = (props) => (
<button className="btn btn-primary" onClick={props.onClick}>{props.label}</button>
);
one more thing, you need to define the click event with signout
button also, like this:
{this.state.active ?
<Button label="Sign OUT" onClick={this.change}/> :
<Button label="Sign in" onClick={this.change}/>
}
change: function () {
this.setState({
active: !this.state.active
})
}
Check working example:
jsfiddle
: https://jsfiddle.net/mtbg3g59/
Codepen
: http://codepen.io/anon/pen/WRLgpp
Upvotes: 1
Reputation: 1440
On page load this.state.active
is set to false therefore the "Sign OUT" button is rendered, which has no onClick attribute. I think you want your code to look something like this:
{this.state.active ?
<Button label="Sign OUT" onClick={this.change}/> :
<Button label="Sign in"/>}
Upvotes: 0
Reputation: 548
Your button doesn't take a prop named onClick so it's normal t hat it does nothing, try to change its definition to this and it should work
const Button = ({label}, {onClick}) => (
<button className="btn btn-primary" onClick={onClick}>{label}</button>
);
Upvotes: 1