react-router-dom#useHistory TypeScript Examples

The following examples show how to use react-router-dom#useHistory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.tsx    From one-platform with MIT License 6 votes vote down vote up
export default function AppSettings () {
  const history = useHistory();
  const { app, loading } = useContext( AppContext );
  const searchParams = useQueryParams();
  const [ activeTab, setActiveTab ] = useState( 'general' );

  useEffect( () => {
    setActiveTab( searchParams.get( 'tab' ) ?? 'general' );
  }, [ searchParams ] );

  const tabs = useMemo(() => [
    { key: 'general', title: 'General', component: General },
    { key: 'permissions', title: 'Permissions', component: Permissions },
    { key: 'api-keys', title: 'API Keys', component: APIKeys },
  ], []);

  const handleTabChange = ( event: React.MouseEvent<HTMLElement, MouseEvent>, tab: string | number ) => {
    const search = searchParams;
    search.set( 'tab', tab.toString() );
    history.push( { search: search.toString() } );
  }

  if ( loading ) {
    return <Loader />;
  }
  return (
    <>
      <Header title="App Settings" />

      <Tabs mountOnEnter activeKey={ activeTab } onSelect={ handleTabChange }>
        { tabs.map( tab => (
          <Tab key={ tab.key } eventKey={ tab.key } title={ tab.title }>
            <tab.component app={app} />
          </Tab>
        ) ) }
      </Tabs>
    </>
  );
}
Example #2
Source File: NavigationContainer.tsx    From Demae with MIT License 6 votes vote down vote up
NavigationBackButton = ({ title, href }: { title: string, href?: string }) => {
	const history = useHistory()
	return (
		<Box paddingX={1}>
			<Button variant="text" size="small" color="primary"
				startIcon={<ArrowBackIosOutlinedIcon />}
				onClick={() => {
					if (href) {
						history.push(href)
					} else {
						history.goBack()
					}
				}}>{title}</Button>
		</Box>
	)
}
Example #3
Source File: TextFieldWithTooltip.tsx    From Cromwell with MIT License 6 votes vote down vote up
export default function TextFieldWithTooltip(props: TextFieldProps & {
    tooltipText?: string;
    tooltipLink?: string;
}) {
    const history = useHistory();

    const openLink = () => {
        if (props.tooltipLink) {
            if (props.tooltipLink.startsWith('http')) {
                window.open(props.tooltipLink, '_blank');
            } else {
                history.push(props.tooltipLink);
            }
        }
    }

    return (
        <TextField
            InputProps={{
                endAdornment: (
                    <InputAdornment position="end">
                        <Tooltip title={props.tooltipText}>
                            <IconButton onClick={openLink}>
                                <HelpOutlineOutlined />
                            </IconButton>
                        </Tooltip>
                    </InputAdornment>
                ),
            }}
            variant="standard"
            {...props}
        />
    )
}
Example #4
Source File: useNetworkSwitching.ts    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
useNetworkSwitching = () => {
  const { connector, deactivate } = useWeb3React();
  const history = useHistory();

  const trySwitching = async (chain: ChainConfig) => {
    if (connector instanceof InjectedConnector) {
      const chainIdHex = `0x${chain.id.toString(16)}`;
      try {
        await window.ethereum?.send('wallet_switchEthereumChain', [
          { chainId: chainIdHex },
        ]);
      } catch (e: any) {
        window.ethereum?.send('wallet_addEthereumChain', [
          {
            chainId: chainIdHex,
            chainName: chain.displayName,
            nativeCurrency: chain.nativeAsset,
            rpcUrls: [chain.rpcUrl, chain.defaultRpc],
            blockExplorerUrls: [chain.blockExplorer],
          },
        ]);
      }
    }

    deactivate();

    history.push(`/${chain.name}`);
  };

  return {
    trySwitching,
  };
}
Example #5
Source File: Sidebar.tsx    From NLW-3.0 with MIT License 6 votes vote down vote up
function Sidebar() {
  const { goBack } = useHistory();

  return (
    <aside className="app-sidebar">
      <img src={mapMarkerImg} alt="Happy" />

      <footer>
        <button type="button" onClick={goBack}>
          <FiArrowLeft size={24} color="#FFF" />
        </button>
      </footer>
    </aside>
  );
}
Example #6
Source File: Mobile.tsx    From GTAV-NativeDB with MIT License 6 votes vote down vote up
function AppBarAction({ text, mobileIcon, buttonProps: { href, target, onClick, ...buttonProps } }: AppBarActionProps) {
  const history = useHistory()

  const handleClick = useCallback(() => {
    if (href) {
      if (href.includes('://') || target) {
        window.open(href, target)
      }
      else {
        history.push(href)
      }
    }

    onClick && onClick()
  }, [href, target, onClick, history])

  return (
    <MenuItem onClick={handleClick}>
      {mobileIcon && <ListItemIcon>
        {React.createElement(mobileIcon)}
      </ListItemIcon>}
      {text}
    </MenuItem>
  )
}
Example #7
Source File: Sidebar.tsx    From happy with MIT License 6 votes vote down vote up
export default function Sidebar() {
  const { goBack } = useHistory();

  return (
    <aside className="app-sidebar">
      <img src={mapMarkerImg} alt="Happy" />

      <footer>
        <button type="button" onClick={goBack}>
          <FiArrowLeft size={24} color="#FFF" />
        </button>
      </footer>
    </aside>
  );
}
Example #8
Source File: room_entrance.tsx    From vorb.chat with GNU Affero General Public License v3.0 6 votes vote down vote up
RoomEntrance: React.SFC = () => {
  const [name, setName] = useState(localStorage.getItem("name") || createName());
  const connect = useRoomConnect();
  const history = useHistory();

  const join = useCallback(() => {
    fill_audio_context_pool();

    localStorage.setItem("name", name);

    connect(name);
  }, [name, connect]);

  const cancel = useCallback(() => {
    history.push('/');
  }, [history]);

  const onKeyDown = useCallback((event: React.KeyboardEvent<HTMLInputElement>) => {
    if(event.keyCode === 13 && !event.shiftKey) {
      event.preventDefault();
      join();
    }
  }, [join]);

  return <Dialog open={true} preventOutsideDismiss>
    <DialogTitle>Select Devices</DialogTitle>
    <DialogContent>
      <TextInput label="Name" value={name} update={setName} onKeyDown={onKeyDown} />
      <br/>
      <InputSelection />
    </DialogContent>
    <DialogActions>
      <DialogButton onClick={cancel} action="close">Leave</DialogButton>
      <DialogButton onClick={join} action="accept" isDefaultAction>Join</DialogButton>
    </DialogActions>
  </Dialog>;
}
Example #9
Source File: AddArticle.tsx    From personal-archive with MIT License 6 votes vote down vote up
AddArticle = () => {
  const history = useHistory()

  return (
    <Container>
      <Button
        type="primarySubtle"
        iconLeft={<PlusCircle/>}
        size="small"
        spaceAfter="small"
        onClick={() => history.push('/articles/new')}
      >
        Add article
      </Button>
    </Container>
  )
}
Example #10
Source File: routes.ts    From gonear-name with The Unlicense 6 votes vote down vote up
useToProfile = (accountId?: string) => {
  const history = useHistory()
  
  return () => {
    if (accountId) {
      history.push(`/profile/${accountId}`)
    } else {
      history.push(`/profile`)
    }
    
  }
}
Example #11
Source File: login.container.tsx    From master-frontend-lemoncode with MIT License 6 votes vote down vote up
LoginContainer: React.FunctionComponent = () => {
  const history = useHistory();

  const loginSucceeded = (isValid: boolean): void => {
    if (isValid) {
      history.push(routes.submoduleList);
    } else {
      // TODO replace
      alert('Invalid login');
    }
  };

  const handleLogin = (login: Login) => {
    isValidLogin(login.user, login.password).then(loginSucceeded);
  };

  return (
    <>
      <LoginComponent onLogin={handleLogin} />
    </>
  );
}
Example #12
Source File: AirdropHeader.tsx    From lobis-frontend with MIT License 6 votes vote down vote up
function AirdropHeader() {
    const [open, setOpen] = useState(false);

    const handleOpen = () => {
        setOpen(true);
    };

    const handleClose = () => {
        setOpen(false);
    };

    let history = useHistory();

    useEscape(() => {
        if (open) handleClose;
        else history.push("/");
    });

    return (
        <div className="bond-header">
            <Link component={NavLink} to="/dashboard" className="cancel-bond">
                <SvgIcon color="primary" component={XIcon} />
            </Link>

            <div className="bond-header-logo">
                <img src={LobisLogo} width={50} />
            </div>
            <div className="bond-header-logo">
                <div className="bond-header-name"></div>
            </div>
        </div>
    );
}
Example #13
Source File: index.tsx    From react-memory-game with MIT License 6 votes vote down vote up
GameWinMessage: React.FC = () => {
  const { isShowingWinModal, setIsShowingWinModal } = useContext(GameContext)

  const onClearGameState = useClearGameState()
  const history = useHistory()
  useCheckGameEnd()

  const onGoBack = (): void => {
    history.goBack()
  }

  const onPlayAgain = (): void => {
    setIsShowingWinModal(false)
    onClearGameState()
  }

  return (
    <AlertModal
      isShowing={isShowingWinModal}
      onCloseModal={onPlayAgain}
      title="Congratulations!"
      message="You proved that your memory is powerful"
    >
      <SecondaryAction onClick={onGoBack}>Go Back</SecondaryAction>
      <PrimaryAction onClick={onPlayAgain}>Play Again</PrimaryAction>
    </AlertModal>
  )
}
Example #14
Source File: DAGContent.tsx    From metaflow-ui with Apache License 2.0 6 votes vote down vote up
DAGContent: React.FC<DAGContentProps> = ({ showFullscreen, graphData, run, stepData }) => {
  const _container = useRef(null);
  const ContainerSize = useComponentSize(_container);
  const WindowSize = useWindowSize();
  const history = useHistory();

  const stepsWithStatus: StepInfoModelWithStatus = Object.keys(graphData.steps).reduce((obj, key) => {
    const addedStatus = {
      ...graphData.steps[key],
      status: stepData.find((sd) => sd.step_name === key)?.status || ('unknown' as const),
    };

    return {
      ...obj,
      [key]: addedStatus,
    };
  }, {});

  function goToStep(stepName: string) {
    history.push(getPath.step(run.flow_id, run.run_number, stepName));
  }

  return (
    <DAGRenderingContainer
      showFullscreen={showFullscreen}
      ref={_container}
      style={{
        transform: 'scale(' + getGraphScale(showFullscreen, ContainerSize, WindowSize) + ')',
      }}
    >
      <ElementContainer variant="root" lined={false}>
        <DAGBranch steps={stepsWithStatus} structure={graphData.graph_structure} goToStep={goToStep} />
      </ElementContainer>
    </DAGRenderingContainer>
  );
}
Example #15
Source File: ScreenC.tsx    From Full-Stack-React-TypeScript-and-Node with MIT License 6 votes vote down vote up
ScreenC: FC<ScreenCProps> = (props) => {
  // useEffect(() => {
  //   setTimeout(() => {
  //     props.history.push("/");
  //   }, 3000);
  // });
  const history = useHistory();
  const { userid } = useParams();

  const onClickGoback = () => {
    // props.history.goBack();
    history.goBack();
  };

  return (
    <div>
      {/* <div>{"Your id is " + props.match.params.userid}</div> */}
      <div>{"Your id is " + userid}</div>
      <div>{props.message}</div>
      <div>
        <button onClick={onClickGoback}>Go back</button>
      </div>
    </div>
  );
}
Example #16
Source File: index.tsx    From Fashionista with MIT License 6 votes vote down vote up
NotFound = () => {
  const { t } = useTranslation();
  const history = useHistory();
  const buttonHandler = () => history.push("/");

  return (
    <div className="container not-found">
      <img src="/img/page-not-found.png" alt="" />
      <h1>Opss!</h1>
      <h3 className="not-found__text">{t("notFoundPage")}</h3>
      <LargeButton onClick={buttonHandler}>
        {t("notFoundButtonMessage")}
      </LargeButton>
    </div>
  );
}
Example #17
Source File: bookmarkItem.tsx    From kinopub.webos with MIT License 6 votes vote down vote up
BookmarkItem: React.FC<Props> = ({ bookmark, className }) => {
  const history = useHistory();
  const source = useMemo(
    () => (bookmark ? `https://dummyimage.com/250x200/222/fff.png&text=${`Фильмов ${bookmark.count}`}` : ''),
    [bookmark],
  );
  const handleOnClick = useCallback(() => {
    if (bookmark?.id) {
      history.push(
        generatePath(PATHS.Bookmark, {
          bookmarkId: bookmark.id,
        }),
        {
          bookmark,
          title: bookmark.title,
        },
      );
    }
  }, [bookmark, history]);

  return <ImageItem onClick={handleOnClick} source={source} caption={bookmark?.title} />;
}
Example #18
Source File: AppOverview.tsx    From one-platform with MIT License 5 votes vote down vote up
function AppOverview () {
  const { app, loading } = useContext( AppContext );
  const history = useHistory();

  const [services] = useState([
    { id: 'op-navbar', name: 'OP Navbar', path: 'op-navbar', isActive: false, disabled: true },
    { id: 'database', name: 'Database', path: 'database', isActive: false, disabled: true },
    { id: 'feedback', name: 'Feedback', path: 'feedback', isActive: false, disabled: true },
    { id: 'search', name: 'Search', path: 'search', isActive: false, disabled: true },
    { id: 'notifications', name: 'Notifications', path: 'notifications', isActive: false, disabled: true },
  ] );

  if ( loading ) {
    return <Loader />;
  }

  return (
    <>
      <Grid hasGutter>
        <GridItem span={ 12 }>
          <Card isRounded className="pf-u-box-shadow-md">
            <CardBody>
              <Flex direction={ { default: 'row' } }>
                <FlexItem flex={ { default: 'flex_1' } }>
                  <Title headingLevel="h1" className="pf-u-mb-sm">{ loading ? 'Loading...' : app.name }</Title>
                  <Flex direction={ { default: 'row' } }>
                    {/* <FlexItem>
                      <Text>Owner: <strong>{ app.owner }</strong></Text>
                    </FlexItem> */}
                    <FlexItem>
                      <Text>Path: <strong>{ app.path }</strong></Text>
                    </FlexItem>
                  </Flex>
                </FlexItem>
                <FlexItem flex={ { default: 'flexNone' } } alignSelf={ { default: 'alignSelfCenter' } }>
                  <a href={ app.path } target="_blank" rel="noreferrer">View App
                &nbsp;<ion-icon name="open-outline"></ion-icon></a>
                </FlexItem>
              </Flex>
            </CardBody>
          </Card>
        </GridItem>
        <GridItem span={ 8 }>
          <Title headingLevel="h3" className="pf-u-my-sm">One Platform Services:</Title>
          <Card isRounded>
            <Menu className="app-service--list-item">
              { services.map( service => (
                <MenuItem
                  className="pf-u-align-items-center"
                  key={ service.id }
                  onClick={ () => history.push( service.path ) }
                  isSelected={false}
                  actions={
                    <MenuItemAction
                    icon={ <Switch
                      isDisabled={true}
                      id={ 'switch-' + service.id }
                      aria-label={ service.name }
                      isChecked={ service.isActive }
                      onChange={ () => { } }/>}
                    /> }>
                  { service.name }
                  </MenuItem>
              ))}
            </Menu>
          </Card>
        </GridItem>
        <GridItem span={4}>
          <Card isRounded>
            <CardBody>
              <Title headingLevel="h5" className="pf-u-mb-sm">SPAship Manager</Title>
              <Text className="pf-u-mb-sm">Manage your SPA deployments from SPAship manager:</Text>
              <Button component="a" variant="secondary" target="_blank" href={ 'https://spaship.one.redhat.com/applications' + app.path + '/details' }>View my SPA&nbsp;<ion-icon name="open-outline"></ion-icon></Button>
            </CardBody>
          </Card>
        </GridItem>
      </Grid>
    </>
  );
}
Example #19
Source File: index.tsx    From Demae with MIT License 5 votes vote down vote up
ProviderInfo = ({ order }: { order: Order }) => {
	const theme = useTheme()
	const history = useHistory()
	const [provider, isLoading] = useDocumentListen<Provider>(Provider, Provider.collectionReference().doc(order.providedBy))

	if (isLoading) {
		return (
			<Paper>
				<DataLoading />
			</Paper>
		)
	}

	if (!provider) {
		return (
			<></>
		)
	}

	return (
		<Box padding={2} onClick={() => history.push(`/providers/${provider.id}`)}>
			<Grid container wrap="nowrap" spacing={2}>
				<Grid item>
					<Avatar variant="rounded" src={provider.coverImageURL()} alt={provider.name} style={{
						height: theme.spacing(8),
						width: theme.spacing(8)
					}}>
						<ImageIcon />
					</Avatar>
				</Grid>
				<Grid item xs zeroMinWidth>
					<Typography variant="subtitle1" gutterBottom>{provider.name}</Typography>
					<Typography variant="body1" color="textSecondary">{provider.caption}</Typography>
					<Divider style={{
						marginTop: theme.spacing(1),
						marginBottom: theme.spacing(1),
					}} />
					<Typography variant="body2" color="textSecondary">{provider.description}</Typography>
				</Grid>
			</Grid>
		</Box>
	)
}
Example #20
Source File: Select.tsx    From Cromwell with MIT License 5 votes vote down vote up
export function Select(props: {
    options?: ({
        value: string | number | undefined;
        label: string;
    } | string | number | undefined)[];
    selectStyle?: React.CSSProperties;
    selectClassName?: string;
    tooltipText?: string;
    tooltipLink?: string;
} & SelectProps<string | number>) {
    const history = useHistory();

    const openLink = () => {
        if (props.tooltipLink) {
            if (props.tooltipLink.startsWith('http')) {
                window.open(props.tooltipLink, '_blank');
            } else {
                history.push(props.tooltipLink);
            }
        }
    }

    return (
        <FormControl
            fullWidth={props.fullWidth}
            style={props.style}
            className={props.className}
        >
            <InputLabel style={props.variant === 'standard' ? {
                marginLeft: '-15px',
                marginTop: '8px',
            } : undefined}
            >{props.label}</InputLabel>
            <MuiSelect
                {...props}
                className={props.selectClassName}
                style={props.selectStyle}
                MenuProps={{
                    style: { zIndex: 10001 }
                }}
                endAdornment={(
                    (props.tooltipText || props.tooltipLink) && (
                        <InputAdornment position="end" sx={{ mr: 1 }}>
                            <Tooltip title={props.tooltipText}>
                                <IconButton onClick={openLink}>
                                    <HelpOutlineOutlined />
                                </IconButton>
                            </Tooltip>
                        </InputAdornment>
                    )
                )}
            >
                {props.options?.map((option) => {
                    const label = typeof option === 'object' ? option.label : option;
                    const value = typeof option === 'object' ? option.value : option;
                    return (
                        <MenuItem value={value} key={value + ''}>{label}</MenuItem>
                    )
                })}
            </MuiSelect>
        </FormControl>
    )
}
Example #21
Source File: GuildsApp.tsx    From dxvote with GNU Affero General Public License v3.0 5 votes vote down vote up
GuildsApp = () => {
  const history = useHistory();

  const isTestingEnv = !window.location?.hostname?.startsWith('dxvote.eth');
  if (!isTestingEnv) {
    history.push('/');
    return null;
  }

  return (
    <ThemeProvider theme={theme}>
      <HashRouter basename="/guilds">
        <GlobalErrorBoundary>
          <WalletWeb3Manager>
            <TransactionsProvider>
              <GuildsContextProvider>
                <GlobalStyle />
                <Header />
                <Container>
                  <GuildAvailabilityProvider>
                    <Switch>
                      <Route exact path="/:chain_name">
                        <LandingPage />
                      </Route>

                      <Route exact path="/:chain_name/:guild_id">
                        <GuildsPage />
                      </Route>
                      <Route path="/:chain_name/:guild_id/proposalType">
                        <ProposalTypes data={ProposalTypesConfig} />
                      </Route>
                      <Route path="/:chain_name/:guild_id/proposal/:proposal_id">
                        <ProposalPage />
                      </Route>
                      <Route path="/:chain_name/:guild_id/create/:proposal_type">
                        <CreateProposalPage />
                      </Route>

                      <Route>
                        <NotFound />
                      </Route>
                    </Switch>
                  </GuildAvailabilityProvider>
                </Container>
              </GuildsContextProvider>
            </TransactionsProvider>
          </WalletWeb3Manager>
        </GlobalErrorBoundary>
      </HashRouter>

      <ToastNotificationContainer autoClose={10000} limit={4} />
    </ThemeProvider>
  );
}
Example #22
Source File: GenerateCodePage.tsx    From GTAV-NativeDB with MIT License 5 votes vote down vote up
function GenerateCodePage() {
  const { language } = useParams<{ language: string }>()
  const history = useHistory()

  const onTabChange = useCallback((e: SyntheticEvent<Element, Event>, language: string) => {
    history.replace(language)
  }, [history])

  return (
    <Box sx={{ py: 2, overflow: 'hidden scroll', flexGrow: 1 }}>
      <Container maxWidth="lg">
        <Typography variant="h4" component="h1" gutterBottom>
          Generate Code
        </Typography>
        <Paper>
          <TabContext value={language}>
            <TabList onChange={onTabChange}>
              <Tab label="C++" value="cpp" />
              <Tab label="Rust" value="rs" />
              <Tab label="C# Enum" value="cs" />
              <Tab label="SHV.NET" value="shvdn" />
              <Tab label="RPH" value="rph" />
            </TabList>
            <Divider />
            <TabPanel value="cpp">
              <CPlusPlus />
            </TabPanel>
            <TabPanel value="rs">
              <Rust />
            </TabPanel>
            <TabPanel value="cs">
              <CSharpEnum />
            </TabPanel>
            <TabPanel value="shvdn">
              Soon&trade;
            </TabPanel>
            <TabPanel value="rph">
              Soon&trade;
            </TabPanel>
          </TabContext>
        </Paper>
      </Container>
    </Box>
  )
}
Example #23
Source File: index.tsx    From gobarber-web with MIT License 5 votes vote down vote up
SignIn: React.FC = () => {
  const formRef = useRef<FormHandles>(null);
  const history = useHistory();

  const { signIn } = useAuth();
  const { addToast } = useToast();

  const handleSubmit = useCallback(
    async (data: SignInFormData) => {
      try {
        formRef.current?.setErrors({});

        const schema = Yup.object().shape({
          email: Yup.string()
            .required('E-mail é obrigatório')
            .email('Digite um e-mail válido'),
          password: Yup.string().required('Senha é obrigatória'),
        });

        await schema.validate(data, { abortEarly: false });

        await signIn({
          email: data.email,
          password: data.password,
        });

        history.push('/dashboard');
      } catch (err) {
        if (err instanceof Yup.ValidationError) {
          const errors = getValidationErrors(err);

          formRef.current?.setErrors(errors);
          return;
        }

        addToast({
          type: 'error',
          title: 'Erro na autenticação',
          description:
            'Ocorreu um error ao fazer login, cheque as credenciais.',
        });
      }
    },
    [signIn, addToast, history],
  );

  return (
    <Container>
      <Content>
        <AnimationContainer>
          <img src={logoImg} alt="GoBarber" />

          <Form ref={formRef} onSubmit={handleSubmit}>
            <h1>Faça seu logon</h1>

            <Input name="email" icon={FiMail} placeholder="E-mail" />

            <Input
              name="password"
              icon={FiLock}
              type="password"
              placeholder="Senha"
            />

            <Button type="submit">Entrar</Button>

            <Link to="/forgot-password">Esqueci minha senha</Link>
          </Form>

          <Link to="/signup">
            <FiLogIn />
            Criar conta
          </Link>
        </AnimationContainer>
      </Content>
      <Background />
    </Container>
  );
}
Example #24
Source File: index.tsx    From rocketseat-gostack-11-desafios with MIT License 5 votes vote down vote up
Import: React.FC = () => {
  const [uploadedFiles, setUploadedFiles] = useState<FileProps[]>([]);
  const history = useHistory();

  async function handleUpload(): Promise<void> {
    const data = new FormData();

    data.append('file', uploadedFiles[0].file);

    try {
      await api.post('/transactions/import', data);
      history.goBack();
    } catch (err) {
      console.log(err.response.error);
    }
  }

  function submitFile(files: File[]): void {
    const newFiles = files.map((file) => ({
      file,
      name: file.name,
      readableSize: String(file.size),
    }));

    setUploadedFiles(newFiles);
  }

  return (
    <>
      <Header size="small" />
      <Container>
        <Title>Importar uma transação</Title>
        <ImportFileContainer>
          <Upload onUpload={submitFile} />
          {!!uploadedFiles.length && <FileList files={uploadedFiles} />}

          <Footer>
            <p>
              <img src={alert} alt="Alert" />
              Permitido apenas arquivos CSV
            </p>
            <button onClick={handleUpload} type="button">
              Enviar
            </button>
          </Footer>
        </ImportFileContainer>
      </Container>
    </>
  );
}
Example #25
Source File: index.tsx    From generator-earth with MIT License 5 votes vote down vote up
Add: FC<{}> = () => {
    const [form] = Form.useForm()
    const routeHistory = useHistory()
    const CONTAINER_ROUTE_PREFIX = useBaseContext()

    // 初始化调用
    useEffect(() => {
        form.setFieldsValue({
            note: 'note'
        })
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])

    async function onFinish(values: object): Promise<void> {
        try {
            // 提交表单最好新一个事务,不受其他事务影响
            await sleep()

            // action
            await request.post('/asset/addAsset', values)

            // 提交后返回list页
            routeHistory.push(`${CONTAINER_ROUTE_PREFIX}/list`)
        } catch (error) {
            console.log(error)
        }
    }

    return (
        <Form className='ui-background' form={form} onFinish={onFinish}>
            <Form.Item name='assetName' label='资产方名称' rules={[{ required: true }]}>
                <Input />
            </Form.Item>

            <Form.Item name='contract' label='签约主体' rules={[{ required: true }]}>
                <Input />
            </Form.Item>

            <Form.Item name='contractDate' label='签约时间' rules={[{ required: true }]}>
                <DatePicker showTime />
            </Form.Item>

            <Form.Item name='contacts' label='联系人'>
                <Input />
            </Form.Item>

            <Form.Item name='contactsPhone' label='联系电话' rules={[{ pattern: Rules.phone, message: '无效' }]}>
                <Input maxLength={11} />
            </Form.Item>

            <Form.Item className='ui-btn-group ui-align-center'>
                <Button type='primary' htmlType='submit'>
                    提交
                </Button>
                <Button htmlType='button' onClick={routeHistory.goBack}>
                    取消/返回
                </Button>
            </Form.Item>
        </Form>
    )

}
Example #26
Source File: Dashboard.tsx    From personal-dj with MIT License 5 votes vote down vote up
Dashboard = () => {
    const [selectedTrack, setSelectedTrack] = useState<SearchResultModel>();
    const [playlistParams, setPlaylistParams] = useState<PlaylistParametersModel>();

    const history = useHistory();
    const query = new URLSearchParams(window.location.search);
    const authToken = query.get("token");

    // Get user token from the URL bar
    useEffect(() => {
        if (authToken) {
            saveToken(authToken);
            // Hide user token so they don't accidentally copy paste it out
            window.location.search = "";
        } else if (!getTokenFromCookies()) {
            tokenError();
            history.push("/");
        }
    });

    const setParameters = (params: PlaylistParametersModel) => {
        setPlaylistParams(params);
    }

    return (
        <div className={"container text-center my-3"}>
            <img src={logo} className={"img-fluid col-lg-2 col-1"}/>
            <hr/>
            <TrackSearchForm setSelected={setSelectedTrack}/>
            {selectedTrack ?
                <PlaylistParametersForm setParameters={setParameters}/> : <></>
            }
            {
                selectedTrack && playlistParams ?
                    <PlaylistResultList parameters={playlistParams}
                                        selectedTrack={selectedTrack}/> :
                    <></>
            }
        </div>
    )
}
Example #27
Source File: index.tsx    From ArCovidRos with GNU Affero General Public License v3.0 5 votes vote down vote up
NoMatch = (): ReactElement => {
  const location = useLocation();

  const { isAuthorized, clearStorage } = session;
  const { ROUTES } = constants;

  const history = useHistory();

  const handleLinkClick = (path: string): void => {
    history.push(path);
  };

  return (
    <div
      style={{
        height: "100vh",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
      }}
    >
      <div
        style={{
          padding: "150px 50px 150px 50px",
          borderRadius: "10px",
          boxShadow: "2px 2px 10px #666 ",
          textAlign: "center",
        }}
      >
        <Typography variant="h6">
          La ruta <code>{location.pathname}</code> es inválida
        </Typography>
        <Button
          style={{
            color: "#00ff8b",
            borderColor: "#00ff8b",
            fontWeight: "bold",
          }}
          variant="outlined"
          onClick={() => handleLinkClick(ROUTES.HOME)}
        >
          Volver al inicio
        </Button>
      </div>
    </div>
  );
}
Example #28
Source File: DPI.tsx    From index-ui with MIT License 5 votes vote down vote up
DpiProductPage = (props: { title: string }) => {
  useEffect(() => {
    document.title = props.title
  }, [props.title])

  const { prices, hourlyPrices, latestPrice, latestMarketCap, latestVolume } =
    useDpiTokenMarketData()
  const { chainId } = useWallet()
  const { dpiBalance, dpiBalancePolygon } = useBalances()
  const { dpiStreamingFee } = useStreamingFee()
  const { dpiTotalSupply } = useTokenSupply()
  const { dpiComponents: components } = useSetComponents()

  const token: ProductToken = {
    ...DefiPulseIndex,
    fees: dpiStreamingFee ? { streamingFee: dpiStreamingFee } : undefined,
  }

  const getTokenBalance = () => {
    if (chainId) {
      if (chainId === MAINNET_CHAIN_DATA.chainId) return dpiBalance
      else if (chainId === POLYGON_CHAIN_DATA.chainId) return dpiBalancePolygon
    }
    return new BigNumber(0)
  }

  const tokenDataProps: TokenDataProps = {
    prices: prices,
    hourlyPrices: hourlyPrices,
    latestPrice: latestPrice,
    latestMarketCap: latestMarketCap,
    latestVolume: latestVolume,
    token: token,
    components: components,
    balance: getTokenBalance(),
    currentSupply: dpiTotalSupply,
  }

  const [, setReferral] = useLocalStorage('referral', '')

  const history = useHistory()
  const params = new URLSearchParams(history.location.search)
  const value = params.get('referral')
  useEffect(() => {
    if (value) setReferral(value)
  }, [value, setReferral])

  return <ProductDataUI tokenDataProps={tokenDataProps} />
}
Example #29
Source File: start_page.tsx    From vorb.chat with GNU Affero General Public License v3.0 5 votes vote down vote up
StartPage: React.SFC = () => {
  const [roomName, setRoomName] = useState("");
  const history = useHistory();

  const defaultName = useMemo(() => {
    const readable = new Readable(true, 5);
    return readable.generate();
  }, []);

  const updateRoom = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    setRoomName(e.target.value);
  }, [setRoomName]);

  const joinRoom = useCallback(() => {
    const room = roomName || defaultName;
    history.push(`/c/${room}`)
  },[roomName]);

  const onKeyDown = useCallback((event: React.KeyboardEvent<HTMLInputElement>) => {
    if(event.keyCode === 13 && !event.shiftKey) {
      event.preventDefault();
      joinRoom();
    }
  }, [joinRoom]);

  return <div className="start_wrapper">
    <div className="start_page">
      <h1>Welcome to <i>vorb.chat</i></h1>
      <p>vorb.chat is ...</p>
      <ul>
        <li>a secure video chat platform</li>
        <li>using peer-to-peer connections and end-to-end encryption</li>
        <li>designed for around two to four participants (depending on bandwidth)</li>
        <li>a tech demo that is in active development</li>
      </ul>
      <p>If you have feedback or want to integrate something like this in your project feel free to conact us at <a href="mailto:[email protected]">[email protected]</a>.</p>
      <div className="join">
        <TextField autoFocus outlined placeholder={defaultName} value={roomName} onChange={updateRoom} onKeyDown={onKeyDown} />
        <Button onClick={joinRoom} outlined><FeatherIcon icon={"play"} /></Button>
      </div>
    </div>
    <Footer />
  </div>
}