Jump to content

Collapsible in React


Pierre314

Recommended Posts

Hi,

I am a noobie and I try to create a collapsible element in my React app. I use the code from W3S (https://www.w3schools.com/howto/howto_js_collapsible.asp) in one my JS file, the CSS part works fine but the JS part does not seem to wrok (the panel does not appear or collapse). I must be wrong with how to implement JS in React, even if it is surely utra basic. What should I modify to make it work?

Thousand thanks

 

import React, { Component } from "react";
import Style from "./Aside.module.scss";

let coll = document.getElementsByClassName("collapsible");
let i;

export default class Aside extends Component {
  render() {
    for (i = 0; i < coll.length; i++) {
      coll[i].addEventListener("click", function () {
        this.classList.toggle("active");
        let content = this.nextElementSibling;
        if (content.style.display === "block") {
          content.style.display = "none";
        } else {
          content.style.display = "block";
        }
      });
    }

    return (
      <div className={Style.aside}>
        <h2>NAVIGATION</h2>
        <button type="button" class={Style.collapsible}>
          Open Collapsible
        </button>
        <div class={Style.content}>
          <p>Lorem ipsum...</p>
        </div>
      </div>
    );
  }
}

 

Edited by Pierre314
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...