bier hier bier hier - 1 year ago 134
React JSX Question

How to collapse a div with reactjs?

I am using reactjs and bootstrap v 3.0 but I can't find any collapse class in there so I defined this in my scss. The problem is that the togglebutton does not work or the toggleevent is not triggered on the div:

toggle(e) {
console.log('testing e',e)
if ( === 'collapse') { = ''
} else { = 'collapse'

This is my button:

<button className="btn btn-block" onClick={() => {

How can I change the className from collapse to and viceversa?
Here is a code sample:Codepen

Answer Source

Your SCSS and your HTML is fine, the problem is in how you used React.

The open/closed state of your component should be represented with a property in this.state, and the toggle() function should simply toggle that property. The render() function, finally, should be responsible of setting the right CSS class on the <div> it renders.

Here's your Codepen updated with my suggestions.

What I did:

  • I defined an initial state in the component constructor: as you can see, I set the open property to false initially;

  • I rewrote the toggle() method, using this.setState() to toggle the value of the open property;

  • I modified the render() function generating the class name of the <div> depending on the state. If the component state is open, the class name will be "collapse in", else it will be only "collapse".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download