react-router#useLocation JavaScript Examples

The following examples show how to use react-router#useLocation. 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: account-nav-menu.js    From albedo with MIT License 6 votes vote down vote up
export default function AccountNavMenu() {
    useLocation()
    useStellarNetwork()

    const links = [
        {link: '/account', icon: 'icon-coins', title: 'Balance'},
        {link: '/wallet/swap', icon: 'icon-switch', title: 'Swap'},
        {link: '/wallet/transfer', icon: 'icon-flash', title: 'Transfer'},
        {link: '/wallet/liquidity-pool', icon: 'icon-liquidity-pool', title: 'Liquidity'},
        {link: '/account-settings', icon: 'icon-settings', title: 'Settings'}
    ]

    return <div className="micro-space navigation">
        {links.filter(link => !!link).map(link => <NavLink key={link.link} {...link}/>)}
    </div>
}
Example #2
Source File: hooks.js    From frontend-app-discussions with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * This hook posts a resize message to the parent window if running in an iframe
 * @param refContainer reference to the component whose size is to be measured
 */
export function useContainerSizeForParent(refContainer) {
  function postResizeMessage(height) {
    postMessageToParent('plugin.resize', { height });
  }

  const location = useLocation();
  const enabled = window.parent !== window;

  const resizeObserver = useRef(new ResizeObserver(() => {
    /* istanbul ignore if: ResizeObserver isn't available in the testing env */
    if (refContainer.current) {
      postResizeMessage(getOuterHeight(refContainer.current));
    }
  }));

  useEffect(() => {
    const container = refContainer.current;
    const observer = resizeObserver.current;
    if (container && observer && enabled) {
      observer.observe(container);
      postResizeMessage(getOuterHeight(container));
    }

    return () => {
      if (container && observer && enabled) {
        observer.unobserve(container);
        // Send a message to reset the size so that navigating to another
        // page doesn't cause the size to be retained
        postResizeMessage(null);
      }
    };
  }, [refContainer, resizeObserver, location]);
}
Example #3
Source File: SuccessPage.jsx    From resilience-app with GNU General Public License v3.0 6 votes vote down vote up
export default function SuccessPage() {
  const { pathname } = useLocation();
  const classes = useStyles();
  return (
    <Box margin="0rem 1rem" display="flex" flexDirection="column">
      {pathname === routes.request.success.donation ? (
        <ByDonationSuccess />
      ) : pathname === routes.request.success.payment ? (
        <ByPaymentSuccess />
      ) : null}

      <Button
        className={classes.button}
        variant="contained"
        color="primary"
        size="large"
        component={Link}
        to={routes.home}
      >
        Continue
      </Button>
    </Box>
  );
}
Example #4
Source File: DiscussionSidebar.jsx    From frontend-app-discussions with GNU Affero General Public License v3.0 6 votes vote down vote up
export default function DiscussionSidebar({ displaySidebar }) {
  const location = useLocation();

  return (
    <div
      className={classNames('flex-column', {
        'd-none': !displaySidebar,
        'd-flex w-25 w-xs-100 w-lg-25 overflow-auto h-100': displaySidebar,
      })}
      style={{ minWidth: '30rem' }}
      data-testid="sidebar"
    >
      <Switch>
        <Route
          path={[Routes.POSTS.PATH, Routes.POSTS.ALL_POSTS, Routes.TOPICS.CATEGORY, Routes.POSTS.MY_POSTS]}
          component={PostsView}
        />
        <Route path={Routes.TOPICS.PATH} component={TopicsView} />
        <Route path={Routes.LEARNERS.POSTS} component={LearnerPostsView} />
        <Route path={Routes.LEARNERS.PATH} component={LearnersView} />
        <Redirect
          from={Routes.DISCUSSIONS.PATH}
          to={{
            ...location,
            pathname: Routes.POSTS.ALL_POSTS,
          }}
        />
      </Switch>
    </div>
  );
}
Example #5
Source File: SearchByArticlesList.js    From Mumble with Apache License 2.0 6 votes vote down vote up
SearchByArticlesList = () => {
  const dispatch = useDispatch();
  const location = useLocation();
  const keyword = location.search;

  const { data } = useSelector((state) => state.articleSearchList);
  const { results: articles } = data;

  useEffect(() => {
    dispatch(searchArticles(keyword));
    return () => {
      dispatch(resetSearchArticles());
    };
  }, [dispatch, keyword]);

  return (
    <div className="category-wrapper" id="category-articles">
      {articles.map((article, index) => (
        <div key={index} className="card">
          <div className="card__body">
            <div className="article-item">
              <Link to={`/article/${article.id}`}>
                <img alt="" className="avatar--md" src={article.thumbnail} />
                <div>
                  <strong>{article.title}</strong>
                </div>
              </Link>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}
Example #6
Source File: checkout.js    From horondi_client_fe with MIT License 6 votes vote down vote up
Checkout = () => {
  const {
    state: { promoCode }
  } = useLocation();
  const { loading, isOrderCreated, order, user } = useSelector(({ Order, User }) => ({
    loading: Order.loading,
    isOrderCreated: Order.isOrderCreated,
    order: Order.order,
    user: User.userData
  }));
  const dispatch = useDispatch();

  const { cart: cartItems, cartOperations } = useCart(user);

  useEffect(() => () => dispatch(setIsOrderCreated(false)), [dispatch, isOrderCreated]);

  const styles = useStyles();

  return (
    <div className={styles.root}>
      {isOrderCreated && <Redirect to={`${pathToThanks}/${order?._id}`} />}
      {!cartItems.length && <Redirect to={pathToMain} />}
      {loading && <Loader />}
      {!loading && (
        <div className={styles.checkoutContainer}>
          <CheckoutForm
            cartItems={cartItems}
            cartOperations={cartOperations}
            promoCode={promoCode}
          />
        </div>
      )}
    </div>
  );
}
Example #7
Source File: RoomNavBar.jsx    From airboardgame with MIT License 6 votes vote down vote up
RoomNavBar = () => {
  const { t } = useTranslation();
  const { room } = useWire("room");
  const { state: { showInvite: initialShowInvite } = {} } = useLocation();
  const [showInvite, setShowInvite] = React.useState(initialShowInvite);

  return (
    <StyledNavBar>
      <div className="nav-left">
        <Brand />
      </div>

      <div className="nav-center">
        <h3>{t("Choose your board")}</h3>
      </div>

      <div className="nav-right">
        <UserList />
        {
          <Touch
            onClick={() => {
              setShowInvite(true);
            }}
            icon="add-user"
            title={t("Invite more player")}
          />
        }
        <WebConferenceButton room={room} />
      </div>
      <InviteModal show={showInvite} setShow={setShowInvite} />
    </StyledNavBar>
  );
}
Example #8
Source File: use-product-filters.spec.js    From horondi_client_fe with MIT License 6 votes vote down vote up
describe('use-product-filters tests', () => {
  it('should handleFilterChange work', () => {
    const { result } = renderHook(() => useProductFilters(mockedFilterParams, mockedFilters));

    expect(useLocation).toBeCalled();
    expect(useTranslation).toBeCalled();
    expect(useHistory).toBeCalled();

    const { filterHandler } = result.current.categories;

    act(() => {
      filterHandler(mockedEvent, mockedQueryName, categoriesList);
    });
    expect(spySearchParamsGet).toBeCalled();
    expect(spySearchParamsSet).toBeCalled();
  });
});
Example #9
Source File: VerifyEmail.js    From Cowin-Notification-System with MIT License 6 votes vote down vote up
VerifyEmail = () =>  {
  const dispatch = useDispatch()
  const search = useLocation().search
  useEffect(() => {
    const email = new URLSearchParams(search).get('email');
    const token = new URLSearchParams(search).get('token');
    dispatch(onEmailVerify(email, token))
  }, [search, dispatch]);
  const verifyEmail = useSelector((state) => state.base.verifyEmail);
  const {
      isDone,
      success,
      email,
  } = verifyEmail;
  return (
    <Row className={'padding--sides width-100 height-100'}>
      <Card className='border-round padding--sides padding--ends margin--ends background-grey center' style={{width: '100%'}}>
        {
          isDone ?
          success ?
          <>
            <CheckCircleOutlined className='f72 text-green' />
            <div className='text-black center margin--top f18'>
              You have successfully subscribed! Your email-{email} will now receive notifications about slot preferences as they become available. 
            </div>
          </> :
          <>
            <CloseCircleOutlined className='f72 text-red' />
            <div className='text-black center margin--top f18'>
              Something went wrong and we could not process your request. Please Try again.
            </div>
          </> :
          <Loader />
        }		
      </Card>
    </Row>
  )
}
Example #10
Source File: TripsMainContainer.js    From airdnd-frontend with MIT License 6 votes vote down vote up
TripsMainContainer = () => {
  // ! redux
  const { data, loading, error } = useSelector(state => state.trips);
  const dispatch = useDispatch();

  // ! hook
  const query = useLocation();
  const { tab } = qs.parse(query.search, {
    ignoreQueryPrefix: true,
  });

  const isActive = tab;

  // ! effect
  useEffect(() => {
    dispatch(fetchTrips(tab || 'upcoming'));
  }, [dispatch, tab]);

  if (loading) return <div>로딩중...</div>;
  if (error) return <div>Error...</div>;
  if (!data) return null;

  return <TripsMain isActive={isActive} />;
}
Example #11
Source File: demo-navigation-view.js    From albedo with MIT License 6 votes vote down vote up
export default function DemoNavigationView() {
    const location = useLocation()
    const {section: activeSection = 'intro'} = parseQuery(location.search)
    return <ul>
        {allSections.map(section => {
            let title = section
            const intentContract = intentInterface[section]
            if (intentContract) {
                title = intentContract.title
            }
            if (section === 'intro') {
                title = 'Introduction'
            }
            return <li key={section} style={{padding: '0.3em 0'}}>
                {section === activeSection ?
                    <b>{title}</b> :
                    <a href={'/playground?section=' + section}>{title}</a>
                }
            </li>
        })}
    </ul>
}
Example #12
Source File: count-per-page.js    From horondi_client_fe with MIT License 6 votes vote down vote up
CountPerPage = () => {
  const { t } = useTranslation();
  const styles = useStyles();
  const history = useHistory();
  const { search } = useLocation();

  const searchParams = new URLSearchParams(search);
  const { countPerPage, page, defaultPage } = URL_QUERIES_NAME;
  const countPerPageText = t('productListPage.countPerPage');

  const pickQuantity = (value) => {
    searchParams.set(page, defaultPage);
    searchParams.set(countPerPage, value);
    history.push(`?${searchParams.toString()}`);
  };
  const productsOnPage = ITEMS_PER_PAGE.map((item) => (
    <Button
      className={
        Number(searchParams.get('countPerPage')) === item.value ? styles.selectedButton : ''
      }
      data-cy={item.title}
      key={item.value}
      type='button'
      value={item.value}
      onClick={() => pickQuantity(item.value)}
      variant={TEXT_FIELD_VARIANT.OUTLINED}
    >
      {item.value}
    </Button>
  ));
  return (
    <div className={styles.pageCounter}>
      <span>{countPerPageText}</span>
      <ButtonGroup className={styles.items}>{productsOnPage}</ButtonGroup>
    </div>
  );
}
Example #13
Source File: OtpStack.jsx    From one-wallet with Apache License 2.0 5 votes vote down vote up
OtpStack = ({ isDisabled, shouldAutoFocus, wideLabel, walletName, otpState, doubleOtp = otpState?.doubleOtp, onComplete, action, label, label2 }) => {
  const { isMobile } = useWindowDimensions()
  const location = useLocation()
  const { otpRef, otp2Ref, otpInput, otp2Input, setOtpInput, setOtp2Input, resetOtp } = otpState || useOtpState()

  useEffect(() => {
    // Focus on OTP 2 input box when first OTP input box is filled.
    if (otpInput.length === 6 && doubleOtp) {
      // For some reason if the OTP input never been focused or touched by user before, it cannot be focused to index 0 programmatically, however focus to index 1 is fine. So as a workaround we focus on next input first then focus to index 0 box. Adding setTimeout 0 to make focus on index 0 run asynchronously, which gives browser just enough time to react the previous focus before we set the focus on index 0.
      otp2Ref?.current?.focusNextInput()
      setTimeout(() => otp2Ref?.current?.focusInput(0), 0)
    } else if (otpInput.length === 6 && onComplete) {
      onComplete()
    }
  }, [otpInput])

  useEffect(() => {
    if (otpInput.length === 6 && doubleOtp && otp2Input.length === 6 && onComplete) {
      onComplete()
    }
  }, [otp2Input])

  useEffect(() => {
    (otpInput || otp2Input) && resetOtp && resetOtp() // Reset TOP input boxes on location change to make sure the input boxes are cleared.
  }, [location])

  return (
    <Space direction='vertical'>
      <Space align='center' size='large' style={{ marginTop: 16 }}>
        <Label wide={wideLabel}>
          <Hint>Code {label || (doubleOtp ? '1' : '')}</Hint>
        </Label>
        <OtpBox
          ref={otpRef}
          value={otpInput}
          onChange={setOtpInput}
          shouldAutoFocus={shouldAutoFocus}
          containerStyle={{ maxWidth: isMobile ? 176 : '100%' }}
          isDisabled={isDisabled}
        />
        <Space direction='vertical' align='center'>
          {walletName &&
            <Tooltip title={`from your Google Authenticator, i.e. ${walletName}`}>
              <QuestionCircleOutlined />
            </Tooltip>}
          {isMobile && <Button type='default' shape='round' icon={<SnippetsOutlined />} onClick={() => { navigator.clipboard.readText().then(t => setOtpInput(t)) }} />}
        </Space>
      </Space>
      {doubleOtp &&
        <Space align='baseline' size='large' style={{ marginTop: 16 }}>
          <Label wide={wideLabel}>
            <Hint>Code {label2 || '2'}</Hint>
          </Label>
          <OtpBox
            ref={otp2Ref}
            value={otp2Input}
            onChange={setOtp2Input}
            containerStyle={{ maxWidth: isMobile ? 176 : '100%' }}
            isDisabled={isDisabled}
          />
          <Space direction='vertical' align='center'>
            {walletName &&
              <Tooltip title={`from your Google Authenticator, i.e. ${walletName} (2nd)`}>
                <QuestionCircleOutlined />
              </Tooltip>}
            {isMobile && <Button type='default' shape='round' icon={<SnippetsOutlined />} onClick={() => { navigator.clipboard.readText().then(t => setOtp2Input(t)) }} />}
          </Space>
        </Space>}
      {action && <Space align='baseline'><Label wide={wideLabel} /><Hint style={{ marginLeft: 16 }}>({action})</Hint></Space>}
    </Space>
  )
}
Example #14
Source File: MenuList.js    From social-media-strategy-fe with MIT License 5 votes vote down vote up
MenuList = () => {
	const classes = useStyles();
	const location = useLocation();
	const { push } = useHistory();
	const { authService } = useOktaAuth();

	const logout = async () => {
		await authService.logout("/");
	};

	return (
		<>
			<Hidden xsDown>
				<Button className={classes.logoButton} onClick={() => push("/home")}>
					<img className={classes.logo} src={logo} alt="SoMe logo" />
				</Button>
			</Hidden>
			<CreatePost />
			<List aria-label="Menu">
				<ListItem button onClick={() => push("/home")}>
					<ListItemIcon>
						<DashboardIcon
							className={
								location.pathname.includes("/home")
									? classes.selectedIcon
									: classes.icon
							}
						/>
					</ListItemIcon>
					<ListItemText primary="Media Manager" />
				</ListItem>
				<ListItem button onClick={() => push("/analytics")}>
					<ListItemIcon>
						<TrendingUpIcon
							className={
								location.pathname.includes("/analytics")
									? classes.selectedIcon
									: classes.icon
							}
						/>
					</ListItemIcon>
					<ListItemText primary="Analytics" />
				</ListItem>
				<ListItem button onClick={() => push("/connect/twitter")}>
					<ListItemIcon>
						<AccountBoxIcon
							className={
								location.pathname.includes("/connect")
									? classes.selectedIcon
									: classes.icon
							}
						/>
					</ListItemIcon>
					<ListItemText primary="Accounts" />
				</ListItem>
			</List>
			<List>
				<ListItem button onClick={logout}>
					<ListItemIcon>
						<ExitToAppIcon color="primary" />
					</ListItemIcon>
					<ListItemText primary="Logout" />
				</ListItem>
			</List>
		</>
	);
}
Example #15
Source File: LearnersView.jsx    From frontend-app-discussions with GNU Affero General Public License v3.0 5 votes vote down vote up
function LearnersView({ intl }) {
  const { courseId } = useParams();
  const location = useLocation();
  const dispatch = useDispatch();
  const orderBy = useSelector(selectLearnerSorting());
  const nextPage = useSelector(selectLearnerNextPage());
  const loadingStatus = useSelector(learnersLoadingStatus());
  const courseConfigLoadingStatus = useSelector(selectconfigLoadingStatus);
  const learnersTabEnabled = useSelector(selectLearnersTabEnabled);
  const learners = useSelector(selectAllLearners);

  useEffect(() => {
    if (learnersTabEnabled) {
      dispatch(fetchLearners(courseId, { orderBy }));
    }
  }, [courseId, orderBy, learnersTabEnabled]);

  const loadPage = async () => {
    if (nextPage) {
      dispatch(fetchLearners(courseId, {
        orderBy,
        page: nextPage,
      }));
    }
  };

  return (
    <div className="d-flex flex-column border-right border-light-300 h-100">
      <LearnerFilterBar />
      <div className="list-group list-group-flush learner">
        {courseConfigLoadingStatus === RequestStatus.SUCCESSFUL && !learnersTabEnabled && (
        <Redirect
          to={{
            ...location,
            pathname: Routes.DISCUSSIONS.PATH,
          }}
        />
        )}
        {courseConfigLoadingStatus === RequestStatus.SUCCESSFUL && learnersTabEnabled && learners.map((learner) => (
          <LearnerCard learner={learner} key={learner.username} courseId={courseId} />
        ))}
        {loadingStatus === RequestStatus.IN_PROGRESS ? (
          <div className="d-flex justify-content-center p-4">
            <Spinner animation="border" variant="primary" size="lg" />
          </div>
        ) : (
          nextPage && loadingStatus === RequestStatus.SUCCESSFUL && (
            <Button onClick={() => loadPage()} variant="primary" size="md">
              {intl.formatMessage(messages.loadMore)}
            </Button>
          )
        )}
      </div>
    </div>
  );
}
Example #16
Source File: product-list-filter.js    From horondi_client_fe with MIT License 5 votes vote down vote up
ProductListFilter = ({ filterParams }) => {
  const { t } = useTranslation();
  const styles = useStyles();
  const history = useHistory();
  const { search } = useLocation();
  const [priceRange, setPriceRange] = useState({});
  const [filters, setFilters] = useState({});
  const filtersOptions = useProductFilters(filterParams, filters);
  const [resetPrices, setResetPrices] = useState(false);

  const searchParams = new URLSearchParams(search);

  const { error, loading } = useQuery(getAllFiltersQuery, {
    onCompleted: (data) => {
      setPriceRange({
        maxPrice: data.getProductsFilters.maxPrice,
        minPrice: data.getProductsFilters.minPrice
      });
      setFilters({
        categories: data.getProductsFilters.categories,
        models: data.getProductsFilters.models,
        patterns: data.getProductsFilters.patterns
      });
    }
  });

  if (error || loading) return errorOrLoadingHandler(error, loading);

  const handleClearFilter = () => {
    const sortQuery = searchParams.get(TEXT_FIELDS.SORT);
    const quantityPerPage = searchParams.get(countPerPage);
    history.push(`${pathToCategory}?page=1&sort=${sortQuery}&countPerPage=${quantityPerPage}`);
    setResetPrices((prev) => !prev);
  };

  const filterButtons = Object.values(filtersOptions).map(
    ({ filterName, productFilter, list, filterHandler, categories }) => (
      <ProductsFiltersContainer
        key={filterName}
        filterName={filterName}
        productFilter={productFilter}
        list={list}
        filterHandler={filterHandler}
        categories={categories}
      />
    )
  );

  return (
    <div>
      <Grid container direction='column' className={styles.wrapper} spacing={2}>
        <Button className={styles.button} data-cy='clear_filter_button' onClick={handleClearFilter}>
          {t('common.clearFilter')}
        </Button>
        <PriceFilter priceRange={priceRange} resetPrices={resetPrices} />
        <HotItemFilter />
        {filterButtons}
      </Grid>
    </div>
  );
}
Example #17
Source File: WalletAuth.jsx    From one-wallet with Apache License 2.0 5 votes vote down vote up
WalletAuth = () => {
  const dispatch = useDispatch()
  const location = useLocation()
  const match = useRouteMatch(Paths.auth)
  const { action } = match ? match.params : {}

  const qs = querystring.parse(location.search)
  const callback = qs.callback && Buffer.from(qs.callback, 'base64').toString()
  const caller = qs.caller
  const network = qs.network
  const { amount, dest, from, calldata } = qs
  const { message: msg, raw, duration, comment } = qs
  // if (!action || !callback || !caller) {
  //   return <Redirect to={Paths.wallets} />
  // }

  useEffect(() => {
    if (network) {
      if (!config.networks[network]) {
        message.error(`App requested invalid network: ${network}`)
      } else {
        message.success(`Switched to: ${network} (per request from ${caller})`, 10)
        dispatch(globalActions.setNetwork(network))
      }
    }
  }, [network])

  if (!action || !callback || !caller) {
    message.error('The app did not specify a callback, an action, or its identity. Please ask the app developer to fix it.')
    return (
      <AnimatedSection
        show
        style={{ minHeight: 320, maxWidth: 720 }}
        title='Broken App'
      >
        <Text>The app did not specify a callback, an action, or its identity. Please ask the app developer to fix it.</Text>
      </AnimatedSection>
    )
  }

  return (
    <>
      {action === 'connect' && <ConnectWallet caller={caller} callback={callback} />}
      {action === 'pay' && <RequestPayment caller={caller} callback={callback} amount={amount} dest={dest} from={from} />}
      {action === 'call' && <RequestCall caller={caller} callback={callback} amount={amount} calldata={calldata} from={from} dest={dest} />}
      {action === 'sign' && <RequestSignature caller={caller} callback={callback} messageB64Encoded={msg} commentB64Encoded={comment} raw={raw} duration={duration} from={from} />}
    </>
  )
}
Example #18
Source File: useQuery.js    From web-client with Apache License 2.0 5 votes vote down vote up
useQuery = () => {
    const location = useLocation();
    return new URLSearchParams(location.search);
}
Example #19
Source File: demo-intent-block-view.js    From albedo with MIT License 5 votes vote down vote up
export default function DemoIntentBlockView({intent}) {
    const intentDefinition = intentInterface[intent]
    if (!intentDefinition) return <div className="space">
        <div className="text-center error">
            Unknown intent: "{intent}"
        </div>
    </div>

    const location = useLocation()

    const {title, description} = intentDefinition

    const [selectedTab, setSelectedTab] = useDependantState(() => {
        const {output} = parseQuery(location.search)
        return output || 'script'
    }, [intent])

    const [allParams, setAllParams] = useDependantState(() => [], [intent]),
        [inProgress, setInProgress] = useDependantState(() => false, [intent]),
        [result, setResult] = useDependantState(() => null, [intent]),
        [error, setError] = useDependantState(() => false, [intent])

    function selectTab(tab) {
        setSelectedTab(tab)
        navigation.navigate(`/playground?section=${intent}&output=${tab}`)
    }

    function exec() {
        setInProgress(true)
        //invoke dynamically
        new Promise(resolve => {
            const res = new Function('albedo', `return ${generateInvocation(intent, allParams)}`)(albedo)
            resolve(res)
        })
            .then(res => {
                setResult(formatOutput(res))
                setError(false)
                setInProgress(false)
            })
            .catch(e => {
                setResult(e instanceof Error ? e.stack : formatOutput(e))
                setError(true)
                setInProgress(false)
            })
    }

    return <div className="intent-block" style={{paddingBottom: '2em'}}>
        <h2 id={intent}>{title} - <code>{intent}</code></h2>
        <div className="intent-description">{description}</div>
        <div className="space">
            <b>Parameters</b>
            {intent==='batch'?
                <DemoBatchParametersView {...{intent, inProgress}} onChange={params => setAllParams(params)}/>:
                <DemoIntentRequestParametersView {...{intent, inProgress}} onChange={params => setAllParams(params)}/>}
        </div>
        <Tabs tabs={getTabs(intent)} selectedTab={selectedTab} onChange={tab => selectTab(tab)}/>
        <DemoIntentExampleView {...{intent, allParams, selectedTab, inProgress}} onExec={exec}/>
        <DemoIntentResultsView {...{result, error}}/>
        <DemoExtraInfoView {...{intent, allParams, result}} />
    </div>
}
Example #20
Source File: hot-item-filter.js    From horondi_client_fe with MIT License 5 votes vote down vote up
HotItemFilter = () => {
  const { t } = useTranslation();
  const styles = useStyles();
  const history = useHistory();
  const { search } = useLocation();

  const { isHotItemFilter, page, defaultPage } = URL_QUERIES_NAME;
  const searchParams = new URLSearchParams(search);
  const hotItemParam = searchParams.get(isHotItemFilter);
  const [hotItem, setHotItem] = useState(false);

  useEffect(() => {
    setHotItem(Boolean(hotItemParam));
  }, [hotItemParam]);

  const handleChange = (event) => {
    if (event.target.checked) {
      searchParams.set(isHotItemFilter, event.target.checked);
    } else {
      searchParams.delete(isHotItemFilter);
    }
    searchParams.set(page, defaultPage);
    history.push(`?${searchParams.toString()}`);
  };

  return (
    <FormGroup data-cy='hot_item_filter'>
      <Typography id='isHot' className={styles.popular} gutterBottom>
        <span className={styles.sectionName}>{t('common.popular')}</span>
        <Switch
          className={styles.popularSwitch}
          color='default'
          checked={hotItem}
          onChange={handleChange}
          name={isHotItemFilter}
          inputProps={{ 'aria-label': 'secondary checkbox' }}
        />
      </Typography>
    </FormGroup>
  );
}
Example #21
Source File: MsgListSectionHeaderContainer.js    From airdnd-frontend with MIT License 5 votes vote down vote up
MsgListSectionHeaderContainer = () => {
  // ! redux
  const popupState = useSelector(state => state.message.popupState.filter);
  const dispatch = useDispatch();
  console.log(popupState);
  // ! hook
  const popupBtnRef = useRef();
  const popupRef = useRef();

  // ! query
  const query = useLocation();
  const { filter } = qs.parse(query.search, {
    ignoreQueryPrefix: true,
  });

  // ! event
  const onClickPopup = useCallback(() => {
    dispatch(openPopup('filter'));
  }, [openPopup]);

  // ! onClickOutside: close popup when clicking outside
  const onClickOutSide = useCallback(
    ({ target }) => {
      if (!popupBtnRef.current || popupBtnRef.current.contains(target))
        return null;
      if (!popupRef.current || popupRef.current.contains(target)) return null;
      return dispatch(closePopup('filter'));
    },
    [popupBtnRef, popupRef],
  );

  // ! effect
  useEffect(() => {
    // ! 렌더링 될때마다 effect 발생...
    // ! 하은이가 알려준 방법 적용하기
    if (!popupState) return;
    document.addEventListener('click', onClickOutSide);
    return () => {
      document.removeEventListener('click', onClickOutSide);
    };
  }, [onClickOutSide, popupState]);

  return (
    <MsgListSectionHeader
      state={filter}
      onClickPopup={onClickPopup}
      popupState={popupState}
      popupBtnRef={popupBtnRef}
      popupRef={popupRef}
    />
  );
}
Example #22
Source File: MobileNavbar.js    From gophie-web with MIT License 5 votes vote down vote up
MobileNavbar = props => {
  const [mobileSearch, setMobileSearch] = useState(false)
  const location = useLocation()
  console.log(location)
  const history = useHistory()

  return (
    <>
      <Style.MobileSearch
        className={mobileSearch ? 'show-mobile-searchbar' : ''}
      >
        <SearchInput
          searchInput={props.searchInput}
          checkInputKey={props.checkInputKey}
          newSearch={props.newSearch}
          checkKeyOnChange={props.checkKeyOnChange}
        />
      </Style.MobileSearch>
      <Style.MobileNavbar>
        <button
          className={`${
            location.pathname === '/Server1' ? 'active' : ''
          } actions-button`}
          onClick={props.handleServerChange}
          onChange={props.handleServerChange}
          data-value='Server1'
          title='Home'
        >
          {location.pathname === '/music' ? <MovieReel /> : <HomeIcon />}
        </button>

        {location.pathname === '/music' ? null : (
          <button
            className={`${
              location.pathname === '/search' ? 'active' : ''
            } actions-button`}
            title='Search'
            onClick={() => setMobileSearch(!mobileSearch)}
          >
            <SearchIcon />
          </button>
        )}

        <button
          className={`${
            location.pathname === '/music' ? 'active' : ''
          } actions-button`}
          title='Music'
          onClick={() => history.push('/music')}
        >
          <MusicNotes />
        </button>

        <button
          className='actions-button'
          title='Change Theme'
          onClick={props.switchTheme}
        >
          {props.theme === 'dark' ? <SunIcon /> : <MoonIcon />}
        </button>
      </Style.MobileNavbar>
    </>
  )
}
Example #23
Source File: use-product-filters.spec.js    From horondi_client_fe with MIT License 5 votes vote down vote up
jest.mock('react-router', () => ({
  useLocation: jest.fn(() => ({
    search: '?page=1&sort=popularity&countPerPage=9&priceFilter=800%2C3600'
  })),
  useHistory: jest.fn(() => ({ push: jest.fn() }))
}));
Example #24
Source File: App.js    From howurls.work with MIT License 5 votes vote down vote up
function App() {
  const defaultLocale =
    localStorage.getItem('locale') ||
    (navigator.languages && navigator.languages[0]) ||
    navigator.language ||
    navigator.userLanguage ||
    'en-US'

  const [locale, setLocale] = useState(defaultLocale)
  const messages = useMemo(() => {
    try {
      return require(`./locales/${locale}.json`)
    } catch (error) {
      // Fallback to English and clean a potentially corrupted storage
      localStorage.removeItem('locale')
      return require('./locales/en-US.json')
    }
  }, [locale])

  const location = useLocation()
  const isRoot = location.pathname === '/'

  return (
    <IntlProvider locale={locale} messages={messages}>
      <LocaleContext.Provider value={{ locale, setLocale }}>
        <Header />
        <main>
          <Grid className="relative">
            <MainContainer>
              {isRoot && (
                <PlaceholderText>
                  <FormattedMessage id="homepage.urlPreview.placeholder" />
                </PlaceholderText>
              )}
              <UrlPreview />
            </MainContainer>
          </Grid>
        </main>
        <Footer />
      </LocaleContext.Provider>
    </IntlProvider>
  )
}
Example #25
Source File: DonateAll.js    From ucurtmetre with GNU General Public License v3.0 5 votes vote down vote up
function DonateAll() {
  const location = useLocation();

  const donateWays = [
    { name: 'BiLira Cüzdanı', component: <BiLiraWalletFlow /> },
    { name: 'Ethereum Cüzdanı', component: <EthereumWallet /> },
    { name: 'Bitcoin', component: <Bitcoin /> },
    { name: 'Banka Havalesi', component: <BankTransferFlow /> },
  ];

  const [activeTab, setActiveTab] = useState(
    donateWays[location.state?.state?.redirected ? 2 : 0]
  );

  const toggleDonator = type => {
    setActiveTab(type);
  };

  return (
    <Card
      className="donate-card"
      title="Destek Yöntemleri"
      desc="Uçurtma gençlerine destekte bulunabilmeniz için aşağıdaki ödeme
    yöntemlerini kullanabilirsiniz."
    >
      <div>
        <nav>
          {donateWays.map(way => (
            <button
              type="button"
              className={cls({
                'button tab-buttons': true,
                active: activeTab.name === way.name,
              })}
              onClick={() => toggleDonator(way)}
              key={way.name}
            >
              {way.name}
            </button>
          ))}
        </nav>
        <div className="donate-tab-content">{activeTab.component}</div>
      </div>
    </Card>
  );
}
Example #26
Source File: index.test.js    From use-react-router-breadcrumbs with MIT License 5 votes vote down vote up
components = {
  Breadcrumbs: ({
    useBreadcrumbs: useBreadcrumbsHook,
    options,
    routes,
    ...forwardedProps
  }) => {
    const breadcrumbs = useBreadcrumbsHook(routes, options);
    const location = useLocation();

    return (
      <h1>
        <span>{location.pathname}</span>
        <div data-test-id="forwarded-props">
          {forwardedProps
            && Object.values(forwardedProps)
              .filter((v) => typeof v === 'string')
              .map((value) => <span key={value}>{value}</span>)}
        </div>
        <div className="breadcrumbs-container">
          {breadcrumbs.map(({ breadcrumb, key }, index) => (
            <span key={key}>
              {breadcrumb}
              {index < breadcrumbs.length - 1 && <i> / </i>}
            </span>
          ))}
        </div>
      </h1>
    );
  },
  BreadcrumbMatchTest: ({ match }) => <span>{match.params.number}</span>,
  BreadcrumbRouteTest: ({ match }) => <span>{match.route?.arbitraryProp}</span>,
  BreadcrumbNavLinkTest: ({ match }) => <a role="link" to={match.pathname}>Link</a>,
  BreadcrumbLocationTest: ({
    location: {
      state: { isLocationTest },
    },
  }) => <span>{isLocationTest ? 'pass' : 'fail'}</span>,
  BreadcrumbExtraPropsTest: ({ foo, bar }) => (
    <span>
      {foo}
      {bar}
    </span>
  ),
  BreadcrumbMemoized: React.memo(() => <span>Memoized</span>),
  // eslint-disable-next-line react/prefer-stateless-function
  BreadcrumbClass: class BreadcrumbClass extends React.PureComponent {
    render() {
      return <span>Class</span>;
    }
  },
  Layout: React.memo(({ children }) => <div>{children}</div>),
}
Example #27
Source File: JobProfilesContainer.js    From ui-data-export with Apache License 2.0 5 votes vote down vote up
JobProfilesContainer = ({
  match,
  resources,
  mutator,
}) => {
  const history = useHistory();
  const location = useLocation();
  const stripes = useStripes();

  const JobProfileDetailsRouteConnected = useMemo(
    () => stripes.connect(JobProfileDetailsRoute, { dataKey: 'job-profile-details' }),
    [stripes]
  );

  return (
    <>
      <JobProfiles
        parentResources={resources}
        parentMutator={mutator}
        {...useJobProfilesProperties(customProperties)}
      />
      <Route
        path={`${match.path}/view/:id`}
        component={JobProfileDetailsRouteConnected}
      />
      <Route
        path={`${match.path}/create`}
        render={() => (
          <CreateJobProfileRoute
            onSubmit={mutator.jobProfiles?.POST}
            onCancel={() => history.push(`${match.path}${location.search}`)}
          />
        )}
      />
      <Route
        path={`${match.path}/edit/:id`}
        render={props => (
          <EditJobProfileRoute
            onSubmit={mutator.jobProfiles.PUT}
            onCancel={() => history.push(`${match.path}${location.search}`)}
            {...props}
          />
        )}
      />
      <Route
        path={`${match.path}/duplicate/:id`}
        render={props => (
          <DuplicateJobProfileRoute
            onSubmit={mutator.jobProfiles.POST}
            onCancel={() => history.push(`${match.path}${location.search}`)}
            {...props}
          />
        )}
      />
    </>
  );
}
Example #28
Source File: TagsPage.js    From Mumble with Apache License 2.0 5 votes vote down vote up
TagsPage = () => {
  const { search } = useLocation();
  const [skill, setSkill] = useState();
  const [results, setResults] = useState({
    results: [],
  });
  const [hasMore, setHasMore] = useState(true);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const params = new URLSearchParams(search);
    setSkill(params.get('skill'));
    setResults({
      results: [],
    });
  }, [search]);

  useEffect(() => {
    if (!skill) return;
    setLoading(true);
    UsersService.getUsersBySkill(skill, page).then((res) => {
      setResults((r) => ({
        ...r,
        results: [...r.results, ...res.results],
      }));
      setHasMore(!!res.next);
      setLoading(false);
    });
  }, [skill, page]);

  const handleLoadMore = () => {
    setPage(page + 1);
  };

  return (
    <Page>
      <section>
        <h1>
          Users who know <b>{skill}</b>
        </h1>
        {results.results.map((user) => (
          <div key={user.id} className="card">
            <div className="card__body">
              <div className="searchItem">
                <div className="searchItem__top">
                  <AuthorBox
                    avatarSrc={getImageUrl(user.profile.profile_pic)}
                    url={`/profile/${user.username}`}
                    name={user.profile.name}
                    handle={user.username}
                    size="md"
                  />
                  <FollowButton userProfile={user.profile} />
                </div>
                <p className="searchItem__bottom">{user.profile.bio}</p>
                <SkillList tags={user.profile.skills} />
              </div>
            </div>
          </div>
        ))}

        {hasMore && (
          <Button
            size="lg"
            disabled={loading}
            onClick={handleLoadMore}
            text={!loading ? 'Load More' : 'Loading...'}
            iconName={loading && 'spinner fa-spin'}
          />
        )}
      </section>
      <section></section>
    </Page>
  );
}
Example #29
Source File: Show.jsx    From one-wallet with Apache License 2.0 4 votes vote down vote up
Show = () => {
  const history = useHistory()
  const location = useLocation()
  const dispatch = useDispatch()

  const wallets = useSelector(state => state.wallet)
  const match = useRouteMatch(Paths.show)
  const { address: routeAddress, action } = match ? match.params : {}
  const oneAddress = util.safeOneAddress(routeAddress)
  const address = util.safeNormalizedAddress(routeAddress)
  const selectedAddress = useSelector(state => state.global.selectedWallet)
  const wallet = wallets[address] || {}
  const [section, setSection] = useState(action)
  const [command, setCommand] = useState(action)
  const network = useSelector(state => state.global.network)
  const [activeTab, setActiveTab] = useState('coins')
  const { expert } = wallet
  const dev = useSelector(state => state.global.dev)

  useEffect(() => {
    if (!wallet.address) {
      return history.push(Paths.wallets)
    }
    if (address && (address !== selectedAddress)) {
      dispatch(globalActions.selectWallet(address))
    }
    const fetch = () => dispatch(balanceActions.fetchBalance({ address }))
    const handler = setInterval(() => {
      if (!document.hidden) { fetch() }
    }, WalletConstants.fetchBalanceFrequency)
    batch(() => {
      fetch()
      dispatch(walletActions.fetchWallet({ address }))
    })
    return () => { clearInterval(handler) }
  }, [address])

  const selectedToken = wallet?.selectedToken || HarmonyONE

  useEffect(() => {
    const m = matchPath(location.pathname, { path: Paths.show })
    const { action } = m ? m.params : {}
    if (action !== 'nft' && action !== 'transfer' && selectedToken.key !== 'one' && selectedToken.tokenType !== ONEConstants.TokenType.ERC20) {
      dispatch(walletActions.setSelectedToken({ token: null, address }))
    }
    if (SpecialCommands.includes(action)) {
      setCommand(action)
    } else {
      setCommand('')
    }
    if (tabList.find(t => t.key === action)) {
      setSection(undefined)
      setActiveTab(action)
      return
    } else if (SectionList.includes(action)) {
      setSection(action)
      return
    }
    setSection('')
  }, [location])

  const showTab = (tab) => { history.push(Paths.showAddress(oneAddress, tab)) }
  const showStartScreen = () => { history.push(Paths.showAddress(oneAddress)) }

  // UI Rendering below
  if (!wallet.address || wallet.network !== network) {
    return <Redirect to={Paths.wallets} />
  }

  const displayTabList = tabList.filter(e => e.tab && ((!e.expert || expert) || (!e.dev || dev)) && (!e.requireNetwork || e.requireNetwork(network)))

  return (
    <>
      {!section &&
        <AnimatedSection
          title={<WalletTitle address={address} onQrCodeClick={() => showTab('qr')} onScanClick={() => showTab('scan')} />}
          tabList={displayTabList}
          activeTabKey={activeTab}
          onTabChange={key => showTab(key)}
          wide
        >
          <Warnings address={address} />
          {activeTab === 'about' && <About address={address} />}
          {activeTab === 'coins' && <Balance address={address} />}
          {activeTab === 'coins' && <ERC20Grid address={address} />}
          {activeTab === 'nft' && <NFTDashboard address={address} />}
          {activeTab === 'help' && <Recovery address={address} />}
          {activeTab === 'swap' && <Swap address={address} />}
          {activeTab === 'gift' && <Gift address={address} />}
          {activeTab === 'qr' && <QRCode address={address} name={wallet.name} />}
          {activeTab === 'scan' && <Scan address={address} />}
          {activeTab === 'call' && <Call address={address} headless />}
          {activeTab === 'sign' && <Sign address={address} headless />}
          {activeTab === 'history' && <TransactionViewer address={address} />}
          <Upgrade address={address} prompt={command === 'upgrade'} onClose={showStartScreen} />
          <CheckForwardState address={address} onClose={() => history.push(Paths.wallets)} />
          <CheckRoots address={address} onClose={() => history.push(Paths.wallets)} />
        </AnimatedSection>}

      {section === 'transfer' && <Send address={address} onClose={showStartScreen} />}
      {section === 'limit' && <Limit address={address} onClose={showStartScreen} />}
      {section === 'recover' && <DoRecover address={address} onClose={showStartScreen} />}
      {section === 'setRecoveryAddress' && <SetRecovery address={address} onClose={showStartScreen} />}
      {section === 'domain' && <PurchaseDomain address={address} onClose={showStartScreen} />}
      {section === 'domainTransfer' && <TransferDomain address={address} onClose={showStartScreen} />}
      {section === 'reclaim' && <Reclaim address={address} onClose={showStartScreen} />}
      {section === 'extend' && <Extend address={address} onClose={showStartScreen} />}
      {section === 'stake' && <Stake address={address} onClose={showStartScreen} />}
      {section === 'unstake' && <Unstake address={address} />}
      {section === 'collectStakeReward' && <CollectStakeReward address={address} />}
    </>
  )
}