/ common / components / UnitDropDown / UnitDropDown.tsx
UnitDropDown.tsx
 1  import React, { Component } from 'react';
 2  import { connect } from 'react-redux';
 3  import { Option } from 'react-select';
 4  
 5  import { AppState } from 'features/reducers';
 6  import * as selectors from 'features/selectors';
 7  import { transactionMetaActions } from 'features/transaction';
 8  import { getNetworkUnit } from 'features/config';
 9  import { walletTypes } from 'features/wallet';
10  import { Query } from 'components/renderCbs';
11  import { Dropdown } from 'components/ui';
12  
13  interface DispatchProps {
14    setUnitMeta: transactionMetaActions.TSetUnitMeta;
15  }
16  
17  interface StateProps {
18    unit: string;
19    tokens: walletTypes.TokenBalance[];
20    allTokens: walletTypes.MergedToken[];
21    showAllTokens?: boolean;
22    networkUnit: string;
23  }
24  
25  class UnitDropdownClass extends Component<DispatchProps & StateProps> {
26    public render() {
27      const { tokens, allTokens, showAllTokens, unit, networkUnit } = this.props;
28      const focusedTokens = showAllTokens ? allTokens : tokens;
29      const options = [networkUnit, ...getTokenSymbols(focusedTokens)];
30      return (
31        <Query
32          params={['readOnly']}
33          withQuery={({ readOnly }) => (
34            <Dropdown
35              options={options}
36              value={unit === 'ether' ? networkUnit : unit}
37              onChange={this.handleOnChange}
38              clearable={false}
39              searchable={options.length > 10}
40              disabled={!!readOnly}
41            />
42          )}
43        />
44      );
45    }
46    private handleOnChange = (unit: Option<string>) => {
47      if (!unit.value) {
48        throw Error('No unit value found');
49      }
50      this.props.setUnitMeta(unit.value);
51    };
52  }
53  const getTokenSymbols = (tokens: (walletTypes.TokenBalance | walletTypes.MergedToken)[]) =>
54    tokens.map(t => t.symbol);
55  
56  function mapStateToProps(state: AppState) {
57    return {
58      tokens: selectors.getShownTokenBalances(state, true),
59      allTokens: selectors.getTokens(state),
60      unit: selectors.getUnit(state),
61      networkUnit: getNetworkUnit(state)
62    };
63  }
64  
65  export const UnitDropDown = connect(mapStateToProps, {
66    setUnitMeta: transactionMetaActions.setUnitMeta
67  })(UnitDropdownClass);