user2932090
user2932090

Reputation: 331

React Collapse - how do I toggle items in the list?

I am displaying a list of items from database and for each item, I have a button "Show more/less". When this is clicked, I want to show/hide the extra content with a nice slide down/up effect. I have implemented this functionality without the slide down/up effect, but want to use React Collapse to make it more user-friendly.

Here's the component where I am trying to implement the React Collapse functionality:

import React from 'react';
import ReactDOM from 'react-dom';
//import axios from 'axios';
import NewPost from './NewPost';
import {Collapse} from 'react-collapse';

class Posts extends React.Component {
    constructor(props) {
        super(props);

        this.toggleClass= this.toggleClass.bind(this);
        this.state = {
            activeIndex: null
        }
    }

    toggleClass(index, e) {     
        this.setState({ activeIndex: this.state.activeIndex === index ? null : index });
    };

    moreLess(index) {
        if (this.state.activeIndex === index) {
            return (
                <span>
                    <i className='fas fa-angle-up'></i> Less
                </span>
            );
        } else {
            return (
                <span>
                    <i className='fas fa-angle-down'></i> More
                </span>
            );                      
        }
    }

  render () {
        let content;

        if (this.props.loading) {
            content = 'Loading...';
        } else {
          content = this.props.posts.map((post, key) => {
            return(
              <li key={key}>
                <div>   
                  <span>{post.id}</span>
                  <span>{post.message}</span>
                  <button className="btn btn-primary btn-xs" onClick={this.toggleClass.bind(this, key)}>
                    {this.moreLess(key)}
                  </button>
                </div>
                <Collapse isOpened={true}>
                  <div className={'alert alert-info msg '+(this.state.activeIndex === key ? "show" : "hide")}>
                    {post.message}
                  </div>
                  </Collapse>
                </li>
              )
            });
        }
        return (
          <div>
            <h1>Posts!</h1>
            <div className="row">
              <div className="col-md-6">
                <ul>
                  {content}
                </ul>
              </div>
            </div>
        </div>
      );
  }
}

export default Posts

But when I click on the More/less button, the content in Collapse doesn't appear - after clicking the button nothing happens.

What am I missing here yet?

Upvotes: 1

Views: 13388

Answers (2)

Elton Marques
Elton Marques

Reputation: 131

if you're using function and hooks I recommend this

import { Collapse } from "react-collapse";
import classNames from "classnames";
import React, { useState} from 'react';

export default function yourFunction() {
    const [activeIndex, setActiveIndex] = useState(null);
    return(
    {groups.map((group, index) => (
        <button className="btn btn-primary navbar-toggler"
                type="button"
                data-toggle="collapse"
                onClick={event => setActiveIndex(
                    activeIndex === index ? null : index
                )}
                data-target="#collapseExample"
                aria-expanded="false"
                aria-controls="collapseExample">
                [CLICK HERE]
        </button>
        <Collapse isOpened={activeIndex === index}>
            <div
                className={classNames("alert alert-info msg", {
                    show: activeIndex === index,
                    hide: activeIndex !== index
                    })}
                >
               <a>[YOUR COLLAPSE CONTENT]</a>
             </div>
        </Collapse>
    )
}

Upvotes: 3

Vikky
Vikky

Reputation: 770

You didn't bind correct check to <Collapse isOpened={true}>. Instead of true, you should put (this.state.)activeIndex === index (current item index) like this:

<Collapse isOpened={this.state.activeIndex === index}>

So it can actually collapse due to activeIndex. I've made codesandbox for you so you can make sure it works: https://codesandbox.io/s/jzx44ynyqw

But I think this is the most important part of it (note that your index was called key, I just renamed it for convenience):

<li key={index}>
  <div>
    <p>{post.title}</p>
    <Collapse isOpened={activeIndex === index}>
      <div
       className={classNames("alert alert-info msg", {
                    show: activeIndex === index,
                    hide: activeIndex !== index
                  })}
      >
       {post.message}
      </div>
     </Collapse>
     <button
       className="btn btn-primary btn-xs"
       onClick={this.toggleClass.bind(this, index)}
      >
       {this.moreLess(index)}
      </button>
    </div>
   </li>

Upvotes: 3

Related Questions