Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save romitgithub/bedb32b532d49f48267ac57a795d2feb to your computer and use it in GitHub Desktop.

Select an option

Save romitgithub/bedb32b532d49f48267ac57a795d2feb to your computer and use it in GitHub Desktop.
import React, { PureComponent } from "react";
class Dropdown extends PureComponent {
constructor(props) {
// spelling mistake change for constructor
super(props);
this.state = {
isOpen: this.props.isInitialStateOpen,
};
}
/**
* Made this an arrow function for binding of this function with the class,
* otherwise it will throw error saying this is undefined.
*/
toggle = () => {
const { isOpen } = this.state;
/**
* Here the state was not toggled, it was being set same as prev state.
* Changed it to toggle the state
*/
this.setState({ isOpen: !isOpen });
};
render() {
const { isOpen } = this.state;
const { label } = this.props;
/**
* Improvement
* Moved the open class on the list to the parent container,
* so that the label can be shown as active dropdown
*/
return (
<div className={`dropdown ${isOpen ? "open" : ""}`}>
<button
type="button"
className={`dropdown-button`}
id="dropdownButton"
aria-haspopup="true"
aria-expanded={isOpen}
onClick={this.toggle}
>
{label}
</button>
<ul
className={`dropdown-menu`}
aria-labelledby="dropdownButton"
role="menu"
>
{this.props.children}
</ul>
</div>
);
}
}
class DropdownItem extends PureComponent {
render() {
/**
* Added return statement here, which is required.
*/
return <a href={this.props.href}>{this.props.children}</a>;
}
}
class ExampleNav extends PureComponent {
render() {
return (
<nav>
<a href="/page1">Page 1</a>
<Dropdown label="More items" isInitialStateOpen={true}>
<DropdownItem href="/page2">Page 2</DropdownItem>
<DropdownItem href="/page3">Page 3</DropdownItem>
<DropdownItem href="/page4">Page 4</DropdownItem>
</Dropdown>
<Dropdown label="Even more items">
<DropdownItem href="/page5">Page 5</DropdownItem>
<DropdownItem href="/page6">Page 6</DropdownItem>
</Dropdown>
</nav>
);
}
}
/**
* Improvements that can be done.
*
* 1) Add default state ability to dropdown.
* Suppose you want to display first dropdown open by default,
* then we can pass a prop to the component for that
*/
export default ExampleNav;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment