Lisa
Lisa

Reputation: 2999

setState did not work for UI change in React and Meteor

I am trying to use a button to toggle the UI display. It will show the corresponding UI when user click the button. And will hide it when user click again. I used the setState to toggle the value of "showItemBank", but the UI only show once, then went back to the invisible as default. Am I missing something important?

Here is the jsx for my App by using Meteor and React.

App = React.createClass ({

mixins: [ReactMeteorData],

getInitialState() {
    return {
      showItemBank: false
    }
},

onItemBankClick(event) {
    this.setState({
        showItemBank : ! this.state.showItemBank
    });

},

render() {
    var classItemBank = ""; 
    var classNewQuestion = ""; 
    if(this.state.showItemBank === false){ 
        classItemBank = "displayNone"; 
    } 
    if(this.state.showItemBank === true){ 
        classItemBank = "displayContent"; 
    }

    return (
        <div className="container">
            <header>
                <form className="new-task" >
                    <div>
                        <button onClick={this.onItemBankClick} className="menu">Select From the Item Bank</button>
                        <button className="menu">Add New Questions</button>
                    </div>
                    <div className={classItemBank}> Hi i am from ItemBank </div>    
                </form>

            </header>
        </div>
    );
}

  });

Upvotes: 0

Views: 263

Answers (2)

Cory Robinson
Cory Robinson

Reputation: 5282

onItemBankClick(event) {

 // stop the event bubbling to parent, in this case <form>
 event.stopPropagation(); 

 // prevent default browser action
 event.preventDefault();

 this.setState({
    showItemBank : ! this.state.showItemBank
 });

}

Upvotes: 1

deowk
deowk

Reputation: 4318

try this

onItemBankClick(event) {
    event.preventDefault();
    this.setState({
        showItemBank : ! this.state.showItemBank
    });

}

buttons will try and submit the page by default

Upvotes: 2

Related Questions