Rotate arrow indicator in React-select v2

北慕城南 提交于 2019-12-06 10:23:04

Technically you can use the style-in-JS props of the v2. Like the following example:

dropdownIndicator: (base, state) => ({
    ...base,
    transition: 'all .2s ease',
    transform: state.isFocused ? 'rotate(180deg)' : null
  })

It seems that the isFocused state isn't bind with the isMenuOpen state but with the real focus state of the container.

A solution is to set closeMenuOnSelect={false} so the user would have to click outside the select and your arrow will flip back.

Or you could change the className props using onMenuOpen and onMenuClose by adding a specific suffix to target your animation.

UPDATE

You can directly access the menuOpen props via the state so no need to manually add class like the following:

dropdownIndicator: (base, state) => ({
  ...base,
  transition: 'all .2s ease',
  transform: state.selectProps.menuIsOpen ? 'rotate(180deg)' : null
})

PLEASE NOTE THAT

In react-select v2.3 a control--menu-is-open has been added directly in the code.

So, based on Laura's response, my solution was to use the onMenuClose and onMenuOpen to set the state of a property in my styled component.

const indicatorStyle = (props: StyledSelectProps & DropdownProps<{}>) => css`
  & .react-select__indicators {
      & .react-select__dropdown-indicator {
        transition: all .2s ease;
        transform: ${props.isOpen && "rotate(180deg)"};
      }
    }
`;

This function is called inside of my styled component's css.

And then in the component I call my styled component, I control the state:

export class Dropdown<TValue> extends React.Component<DropdownProps<TValue>> {
  public state = { isOpen: false };

  private onMenuOpen = () => this.setState({ isOpen: true });
  private onMenuClose = () => this.setState({ isOpen: false });

  public render() {
    const { ...props } = this.props;
    const { isOpen } = this.state;
    return (
      <StyledSelect {...props} isOpen={isOpen} onMenuOpen={this.onMenuOpen} onMenuClose={this.onMenuClose} />
    );
  }
}

A bit convoluted but it works for now.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!