UNPKG

@eureca/eureca-ui

Version:

UI component library of Eureca's user and admin apps

96 lines (86 loc) 2.4 kB
import React, { useState } from 'react'; import PropTypes from 'prop-types'; import { Box, Typography, useTheme } from '@material-ui/core'; import { Flex } from '../Flex'; import { colors } from '../../theme/colors'; const styles = { backgroundBox: { backgroundColor: colors.gray5, borderRadius: 12, }, selectedBox: { backgroundColor: colors.green1, borderRadius: 12, zIndex: 5, }, }; function SwitchButton({ options, onChange, buttonStyle, boxStyle }) { const muiTheme = useTheme(); const [currentPosition, setCurrentPosition] = useState(0); const [clientWidth, setClientWidth] = useState(null); const imageContainerRef = imageContainerRef => { if (imageContainerRef !== null) { setClientWidth(imageContainerRef.clientWidth); } }; const cellWidth = clientWidth / options.length; return ( <Flex directionRow alignCenter justifySpaceBetween position="relative" height={muiTheme.spacing(5)} cursorPointer style={{ ...styles.backgroundBox, ...boxStyle }} ref={imageContainerRef} > {options.flatMap((item, index) => ( <Flex key={`button-item-${index}`} justifyCenter alignCenter width={cellWidth} height={muiTheme.spacing(5)} onClick={() => { setCurrentPosition(index); onChange(item.value); }} > <Typography variant="body1" style={{ color: currentPosition === index ? colors.white : colors.gray3, zIndex: 10, }} > {item.name} </Typography> </Flex> ))} <Box position="absolute" left={0} width={cellWidth} height={muiTheme.spacing(5)} style={{ ...styles.selectedBox, transform: currentPosition !== 0 && `translateX(${currentPosition * cellWidth}px)`, transition: clientWidth && 'all 0.15s ease-in-out', ...buttonStyle, }} /> </Flex> ); } SwitchButton.propTypes = { options: PropTypes.arrayOf( PropTypes.shape({ name: PropTypes.string.isRequired, value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), }).isRequired ).isRequired, style: PropTypes.object, onChange: PropTypes.func, }; export { SwitchButton };