0

I'm working on a small component which is essentially a button that allows a user to click to see a small shopping cart overlay.

If "showCart" is false (AKA the button is not clicked), the cart should be invisible. If the button is clicked, "showCart" should become true and thus render the component.

I try clicking on the button and while I do get my console.log message "Button clicked", my Cart overlay doesn't appear. Can anyone give me some insight as to why this isn't working?

class ViewCart extends React.Component {
  constructor(props) {
    super(props);
    this.state = { showCart: false }
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState ={ showCart: true} 
    console.log("button clicked")

  }
  render() { 
    return (
      <div> 
      <button onClick={this.handleClick}> Show Cart 
        {this.state.showCart ? <Cart />: null }
        </button>

        </div>
        );
  }
}
0

2 Answers 2

2

You are not changing state in right manner, Code for change state will be like this this.setState({ showCart: true}) Replace handleClick function from below code.

 handleClick() {
    this.setState({ showCart: true}) 
    console.log("button clicked")
  }
Sign up to request clarification or add additional context in comments.

Comments

0

You update your state the wrong way :)

handleClick() {
  this.setState({ showCart: true})
  console.log("button clicked")
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.