import * as React from 'react' ; import { Children , cloneElement , isValidElement , ReactElement } from 'react' ; import PropTypes from 'prop-types' ; import Tabs , { TabsProps } from '@material-ui/core/Tabs' ; import { useLocation } from 'react-router-dom' ; const TabbedFormTabs = ( props ) => { const { children , classes , url , syncWithLocation , value , ... rest } = props ; const location = useLocation ( ) ; const validTabPaths = Children . map ( children , ( tab , index ) => { if ( ! isValidElement ( tab ) ) return undefined ; return getTabFullPath ( tab , index , url ) ; } ) ; const tabValue = validTabPaths . includes ( location . pathname ) ? location . pathname : validTabPaths [ 0 ] ; return ( < Tabs value = { syncWithLocation ? tabValue : value } indicatorColor = "primary" { ... rest } > { Children . map ( children , ( tab , index ) => { if ( ! isValidElement < any > ( tab ) ) return null ; const tabPath = getTabFullPath ( tab , index , url ) ; return cloneElement ( tab , { intent : 'header' , value : syncWithLocation ? tabPath : index , classes , syncWithLocation , } ) ; } ) } < /Tabs>); } ; TabbedFormTabs . propTypes = { children : PropTypes . node , classes : PropTypes . object , url : PropTypes . string , tabsWithErrors : PropTypes . arrayOf ( PropTypes . string ) , } ; export const getTabFullPath = ( tab , index , baseUrl ) : string => `${ baseUrl }${ tab . props . path ? `/${ tab . props . path }` : index > 0 ? `/${ index }` : '' }` . replace ( '//' , '/' ) ; export interface TabbedFormTabsProps extends TabsProps { classes ? : any ; url ? : string ; tabsWithErrors ? : string [ ] ; syncWithLocation ? : boolean ; } export default TabbedFormTabs ;