2

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"))

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks that help a lot
glad, to help you :)
1

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>
);

Comments

0

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"/>}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.