Skip to content

Instantly share code, notes, and snippets.

@ChiKaLiO
Created July 7, 2022 16:19
Show Gist options
  • Save ChiKaLiO/b78dfc764a030b9a124a456bb7212d55 to your computer and use it in GitHub Desktop.
Save ChiKaLiO/b78dfc764a030b9a124a456bb7212d55 to your computer and use it in GitHub Desktop.
import React, { PureComponent } from 'react';
class Dropdown extends PureComponent {
// Bug: wrong name
constructor(props) {
super(props);
this.state = {
isOpen: false,
selectedItem: '',
};
}
// Bug: bind or change to arrow function
toggle = () => {
const { isOpen } = this.state;
// Bug: wrong state update
this.setState({ isOpen: !isOpen });
};
onClickItem = val => {
const { selectedItem } = this.state;
const { onChange } = this.props;
if (val !== selectedItem) {
this.setState({ selectedItem: val });
this.toggle();
if (onChange) {
onChange(val);
}
}
};
render() {
const { isOpen, selectedItem } = this.state;
const { label } = this.props;
console.log('selectedItem', selectedItem);
const childrenWithProps = React.Children.map(this.props.children, child => {
return React.isValidElement(child)
? React.cloneElement(child, { onClickItem: this.onClickItem, selectedItem })
: child;
});
return (
{label}
<ul
className={`${isOpen ? 'dropdown-open' : ''} dropdown-menu`}
aria-labelledby="dropdownButton"
role="menu"
>
{/* Bug: Add condition */}
{isOpen && childrenWithProps}
</ul>
</div>
);
}
}
class DropdownItem extends PureComponent {
handleClick = () => {
const { href, onClickItem } = this.props;
onClickItem(href);
};
render() {
const { children, selectedItem, href } = this.props;
const isSelected = selectedItem === href;
return (
<li style={{ color: isSelected ? 'red' : '' }} onClick={this.handleClick}>
{children}
);
}
}
class ExampleNav extends PureComponent {
render() {
return (
<nav>
<a href="/page1">Page 1</a>
<Dropdown label="More items">
<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>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment