react#useState TypeScript Examples

The following examples show how to use react#useState. 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: register.tsx    From 0Auth with MIT License 7 votes vote down vote up
function Register({ submit }: UserProps) {
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [age, setAge] = useState('');
  const [address, setAddress] = useState('');
  const submitInfo = () => submit(name, phone, age, address);

  return (
    <div className="User">
      <h2>Register Info</h2>
      <form noValidate>
        <TextField required id="name" value={name} onChange={e => setName(e.target.value)} label="Name"/><br/>
        <TextField required id="phone" value={phone} onChange={e => setPhone(e.target.value)} label="Phone"/><br/>
        <TextField required id="age" value={age} onChange={e => setAge(e.target.value)} label="Age"/><br/>
        <TextField required id="address" value={address} onChange={e => setAddress(e.target.value)} label="Address"/><br/><br/>
        <Button variant="contained" color="primary" onClick={submitInfo}>
          Submit
        </Button>
      </form>
    </div>
  );
}
Example #2
Source File: usePagination.tsx    From one-platform with MIT License 7 votes vote down vote up
usePagination = ({ page = 1, perPage = 20 }: Props): UsePaginationReturn => {
  const [pagination, setPagination] = useState({ page, perPage });

  const onSetPage = useCallback((pageNumber: number): void => {
    setPagination((state) => ({ ...state, page: pageNumber }));
  }, []);

  const onPerPageSelect = useCallback((perPageSelected: number) => {
    setPagination((state) => ({ ...state, perPage: perPageSelected }));
  }, []);

  const onResetPagination = useCallback(() => {
    setPagination({ page, perPage });
  }, [page, perPage]);

  return {
    pagination,
    onSetPage,
    onPerPageSelect,
    onResetPagination,
  };
}
Example #3
Source File: Dialog.tsx    From Demae with MIT License 7 votes vote down vote up
DialogProvider = ({ children }: { children: any }) => {
	const [state, setState] = useState<Prop>({
		title: undefined,
		body: undefined,
		actions: []
	})
	const open = !!state.title || !!state.body
	const onClose = () => {
		setState({
			title: undefined,
			body: undefined,
			actions: []
		})
	}
	const showDialog = (title: string | undefined, body: string | undefined, actions: Action[]) => {
		setState({ title, body, actions })
	}
	return (
		<DialogContext.Provider value={[showDialog, onClose, open]}>
			<_Dialog open={open} title={state.title} body={state.body} actions={state.actions} onClose={onClose} />
			{children}
		</DialogContext.Provider>
	)
}
Example #4
Source File: movies.tsx    From 0Auth with MIT License 6 votes vote down vote up
function Movies({ properties, sign }: MoviesProps) {
  const [movieList, setMovieList] = useState<MovieType[]>([]);
  const movieUrl = 'http://127.0.0.1:3000/movies';
  if (movieList.length === 0) {
    fetch(movieUrl)
      .then(res => res.json() as unknown as MovieType[])
      .then(res => res.map((movie, id) => ({ ...movie, id })))
      .then(res => setMovieList(res));
  }
  const bookMovie = (id: number) => {
    const url = `http://127.0.0.1:3000/view/movie/${id}`;
    fetch(url, {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      method: 'POST',
      body: JSON.stringify({ properties, sign }),
    }).then(res => res.json() as unknown as Ticket)
      .then(res => {
        movieList[id].ticket = res;
        setMovieList([...movieList]);
      });
  };

  return (
    <div className="Movies">
      <h2>Book Movie</h2>
      {movieList.map(movie => <Movie bookMovie={bookMovie} {...movie}/>)}
    </div>
  );
}
Example #5
Source File: index.tsx    From vscode-crossnote with GNU Affero General Public License v3.0 6 votes vote down vote up
function GitHubGistWidget(props: WidgetArgs) {
  const classes = useStyles(props);
  const { t } = useTranslation();
  const [url, setURL] = useState<string>("");

  const setGistURL = useCallback(
    (url: string) => {
      try {
        const location = new URL(url);
        if (location.host !== "gist.github.com") {
          return;
        } else {
          props.setAttributes({
            url: location.origin + location.pathname,
          });
        }
      } catch (error) {}
    },
    [props]
  );

  if (props.attributes["url"]) {
    return (
      <Box className={"preview github-gist"} style={{ whiteSpace: "normal" }}>
        <Gist url={props.attributes["url"]}></Gist>
        {!props.isPreview && (
          <Box className={clsx(classes.actionButtonsGroup)}>
            <IconButton onClick={() => props.removeSelf()}>
              <TrashCanOutline></TrashCanOutline>
            </IconButton>
          </Box>
        )}
      </Box>
    );
  }

  if (props.isPreview) {
    return null;
  }

  return (
    <Card elevation={2} className={clsx(classes.card)}>
      <Typography variant={"h5"}>
        {t("widget/crossnote.github_gist/title")}
      </Typography>
      <TextField
        label={t("widget/crossnote/github_gist/enter-github-gist-url")}
        placeholder={"https://gist.github.com/..."}
        value={url}
        onChange={(event) => setURL(event.target.value)}
        fullWidth={true}
        onKeyUp={(event) => {
          if (event.which === 13) {
            setGistURL(url);
          }
        }}
      ></TextField>
      <Box className={clsx(classes.actionButtonsGroup)}>
        <Tooltip title={t("general/Delete")}>
          <IconButton onClick={() => props.removeSelf()}>
            <TrashCan></TrashCan>
          </IconButton>
        </Tooltip>
      </Box>
    </Card>
  );
}
Example #6
Source File: useDebounce.tsx    From one-platform with MIT License 6 votes vote down vote up
useDebounce = <T extends unknown>(value: T, delay = 500): T => {
  // State and setters for debounced value
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(
    () => {
      // Update debounced value after delay
      const handler = setTimeout(() => {
        setDebouncedValue(value);
      }, delay);

      // Cancel the timeout if value changes (also on delay change or unmount)
      // This is how we prevent debounced value from updating if value is changed ...
      // .. within the delay period. Timeout gets cleared and restarted.
      return () => {
        clearTimeout(handler);
      };
    },
    [value, delay] // Only re-call effect if value or delay changes
  );

  return debouncedValue;
}
Example #7
Source File: Drawer.tsx    From Demae with MIT License 6 votes vote down vote up
DrawerProvider = ({ children }: { children: any }) => {
	const [state, setState] = useState<Prop>({
		anchor: 'bottom',
		component: undefined
	})
	const open = !!state.component
	const onClose = () => {
		setState({ component: undefined, anchor: 'bottom' })
	}
	const showDrawer = (component: React.ReactNode, anchor: Anchor = 'bottom') => {
		setState({ component, anchor })
	}
	return (
		<DrawerContext.Provider value={[showDrawer, onClose, open]}>
			<_Drawer open={open} anchor={state.anchor} onClose={onClose}>{state.component}</_Drawer>
			{children}
		</DrawerContext.Provider>
	)
}
Example #8
Source File: useInput.tsx    From react_admin with MIT License 6 votes vote down vote up
useInput = (initialValue: string): InputProps => {
  const [val, setVal] = useState<string>(initialValue);
  const setDoubleValue = (
    e: React.ChangeEvent<HTMLInputElement & HTMLTextAreaElement>
  ): void => {
    setVal(e.target.value);
  };
  return {
    val,
    onChange: setDoubleValue,
  };
}
Example #9
Source File: _app.tsx    From 35d-blog with MIT License 6 votes vote down vote up
App = ({ Component, pageProps }) => {
  const router = useRouter()

  let defaultTheme
  if (process.browser) {
    defaultTheme = window.localStorage.getItem('35d_theme') || 'LIGHT'
  }
  const [theme, setTheme] = useState(defaultTheme)

  const toggleDarkMode = () => {
    if (process.browser) {
      window.localStorage.setItem('35d_theme', theme === 'LIGHT' ? 'DARK' : 'LIGHT')
    }
    theme === 'LIGHT' ? setTheme('DARK') : setTheme('LIGHT')
  }

  return (
    <ThemeProvider theme={theme === 'LIGHT' ? lightTheme : darkTheme}>
      <>
        <DarkModeContext.Provider value={{ theme, toggleDarkMode }}>
          <div className="w-full max-w-3xl mx-auto flex flex-wrap items-start overflow-hidden">
            <Navigation />
            <main className="w-full sm:w-3/4 ml-0 sm:ml-1/4 min-h-screen">
              <Breadcrumbs route={router.route} />
              <Component {...pageProps} className="w-full sm:w-3/4 sm:-mt-1 ml-0 sm:ml-1/4" />
            </main>
            <Footer />
          </div>
        </DarkModeContext.Provider>
      </>
    </ThemeProvider>
  )
}
Example #10
Source File: CollapsibleText.tsx    From 3Speak-app with GNU General Public License v3.0 6 votes vote down vote up
export function CollapsibleText(props: any) {
  const [collapsed, setCollapsed] = useState(true)

  const handleClick = (e) => {
    setCollapsed(!collapsed)
  }

  return (
    <>
      <div
        style={{
          maxHeight: collapsed ? '200px' : 'initial',
          overflow: 'hidden',
        }}
      >
        {props.children}
      </div>
      <div
        className="text-center"
        onClick={handleClick}
        id="videoAboutCollapse"
        style={{ cursor: 'pointer', borderTop: '1px solid rgba(0,0,0,0.2)' }}
      >
        {collapsed ? <FaChevronDown /> : <FaChevronUp />}
        {collapsed ? 'Show more' : 'Show less'}
      </div>
    </>
  )
}
Example #11
Source File: index.tsx    From landy-react-template with MIT License 6 votes vote down vote up
ScrollToTop = () => {
  const [showScroll, setShowScroll] = useState(false);

  const checkScrollTop = (event: any) => {
    const offsetFromTop = getScroll(event.target, true);

    if (!showScroll && offsetFromTop > 350) {
      setShowScroll(true);
    } else if (offsetFromTop <= 350) {
      setShowScroll(false);
    }
  };

  useEffect(() => {
    window.addEventListener("scroll", checkScrollTop);
    return () => {
      window.removeEventListener("scroll", checkScrollTop);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const scrollUp = () => {
    const element = document.getElementById("intro") as HTMLDivElement;
    element.scrollIntoView({
      behavior: "smooth",
      block: "end",
      inline: "nearest",
    });
  };

  return (
    <ScrollUpContainer onClick={scrollUp} show={showScroll}>
      <SvgIcon src="scroll-top.svg" width="20px" height="20px" />
    </ScrollUpContainer>
  );
}
Example #12
Source File: useMediaQuery.ts    From akashlytics with GNU General Public License v3.0 6 votes vote down vote up
export function useMediaQuery(query) {
  const [matches, setMatches] = useState(false);

  useEffect(() => {
    const media = window.matchMedia(query);
    if (media.matches !== matches) {
      setMatches(media.matches);
    }
    const listener = () => {
      setMatches(media.matches);
    };
    media.addEventListener("change", listener);
    return () => media.removeEventListener("change", listener);
  }, [matches, query]);

  return matches;
}
Example #13
Source File: App.tsx    From overwolf-modern-react-boilerplate with MIT License 6 votes vote down vote up
App = () => {
  const [page, setPage] = useState<string>('')

  useEffect(() => {
    async function preLoad() {
      if (process.env.NODE_ENV === 'development') {
        //you can set the current window to dev if you want to see the dev page <Normal Browser>
        setPage(WINDOW_NAMES.DESKTOP)
      } else {
        const currentWindow = await getCurrentWindow()
        setPage(currentWindow)
        console.info(
          '[? overwolf-modern-react-boilerplate][? src/app/App.tsx][? useEffect - preLoad]',
          JSON.stringify({ currentWindow }, null, 2),
        )
      }
    }
    preLoad()
  }, [])
  //this is fallback for the loading current screen
  return (
    <Suspense fallback={<Loading />}>
      <CurrentPage page={page} />
    </Suspense>
  )
}
Example #14
Source File: index.tsx    From react-doc-viewer with Apache License 2.0 6 votes vote down vote up
TIFFRenderer: DocRenderer = (props) => {
  const {
    mainState: { currentDocument },
  } = props;

  const [loadedCanvas, setLoadedCanvas] = useState(false);
  const [corruptedFile, setCorruptedFile] = useState(false);

  useEffect(() => {
    if (!currentDocument || loadedCanvas) return;

    var canvas = document.getElementById("tiff-img");
    try {
      canvas && parseTIFF(currentDocument.fileData as ArrayBuffer, canvas);
      setLoadedCanvas(true);
    } catch (error) {
      setCorruptedFile(true);
    }
  }, []);

  if (corruptedFile) {
    return (
      <ImageProxyRenderer {...props}>
        <div>Your file is corrupted. Please check it on your machine.</div>
      </ImageProxyRenderer>
    );
  }

  return (
    <ImageProxyRenderer {...props}>
      <Canvas id="tiff-img" />
    </ImageProxyRenderer>
  );
}
Example #15
Source File: index.ts    From react-useStateRef with MIT License 6 votes vote down vote up
useStateRef: UseStateRef = <S>(initialState?: S | (() => S)) => {
  const [state, setState] = useState(initialState);
  const ref = useRef(state);

  const dispatch: typeof setState = useCallback((setStateAction:any) => {
    ref.current = isFunction(setStateAction) ? setStateAction(ref.current) : setStateAction;

    setState(ref.current);
  }, []);

  return [state, dispatch, ref];
}
Example #16
Source File: target.tsx    From anchor-web-app with Apache License 2.0 6 votes vote down vote up
DeploymentTargetProvider = (props: UIElementProps) => {
  const { children } = props;

  const [storedChain, setChain] = useLocalStorage<string>(
    '__anchor_deployment_target__',
    DEPLOYMENT_TARGETS[0].chain,
  );

  const chain = safeChain(storedChain);

  const [target, updateTarget] = useState(
    DEPLOYMENT_TARGETS.filter((target) => target.chain === chain)[0],
  );

  const value = useMemo(() => {
    return {
      target,
      updateTarget: (chainOrTarget: Chain | DeploymentTarget) => {
        let found =
          typeof chainOrTarget === 'string'
            ? DEPLOYMENT_TARGETS.find((t) => t.chain === chainOrTarget)
            : chainOrTarget;

        if (found) {
          updateTarget(found);
          setChain(found.chain);
        }
      },
    };
  }, [target, updateTarget, setChain]);

  return (
    <DeploymentTargetContext.Provider value={value}>
      {children}
    </DeploymentTargetContext.Provider>
  );
}
Example #17
Source File: App.tsx    From 0Auth with MIT License 5 votes vote down vote up
function App() {
  const [properties, setProperties] = useState<Property[]>([]);
  const [sign, setSign] = useState<Signature | undefined>(undefined);
  const init = () => {
    if (properties.length === 0) {
      const decrypted = getSignature(StorageType.LocalStorage);
      if (decrypted?.properties !== undefined) setProperties(decrypted.properties);
      if (decrypted?.sign !== undefined) setSign(decrypted.sign)
    }
  }
  const submit = (name: string, phone: string, age: string, address: string) => {
    const object = { name, phone, age, address };
    const properties = objectToProperty(object);
    setProperties(properties);
    const url = 'http://127.0.0.1:3000/register';
    fetch(url, {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      method: 'POST',
      body: JSON.stringify({ properties }),
    }).then(res => res.json() as unknown as Signature)
      .then(res => {
        storeSignature(properties, res, StorageType.LocalStorage);
        setSign(res)
      });
  };
  init();

  return (
    <div className="App">
      {
        sign === undefined
          ? (
            <Register submit={submit}/>
          )
          : (
            <Movies properties={properties!} sign={sign}/>
          )
      }
    </div>
  );
}
Example #18
Source File: index.tsx    From vscode-crossnote with GNU Affero General Public License v3.0 5 votes vote down vote up
function KanbanColumnHeaderDisplay(props: KanbanColumnHeaderProps) {
  const classes = useStyles(props);
  const { t } = useTranslation();
  const column = props.column;
  const board = props.board;
  const isPreview = props.isPreview;
  const refreshBoard = props.refreshBoard;
  const [clickedTitle, setClickedTitle] = useState<boolean>(false);
  const [titleValue, setTitleValue] = useState<string>(column.title);

  useEffect(() => {
    if (!clickedTitle && titleValue !== column.title) {
      column.title = titleValue || t("general/Untitled");
      setTitleValue(column.title);
      refreshBoard(board);
    }
  }, [clickedTitle, board, column.title, titleValue, t, refreshBoard]);

  return (
    <Box className={clsx(classes.columnHeader)}>
      <Box>
        {clickedTitle ? (
          <TextField
            value={titleValue}
            onChange={(event) => {
              setTitleValue(event.target.value);
            }}
            onBlur={() => {
              setClickedTitle(false);
            }}
            onKeyUp={(event) => {
              if (event.which === 13) {
                setClickedTitle(false);
              }
            }}
          ></TextField>
        ) : (
          <Typography
            variant={"body1"}
            style={{ cursor: "text" }}
            onClick={() => {
              if (!isPreview) {
                setClickedTitle(true);
              }
            }}
          >
            {titleValue}
          </Typography>
        )}
      </Box>
      {!isPreview && (
        <Box>
          <IconButton
            onClick={() => {
              const card: KanbanCard = {
                id: Date.now(),
                title: "", //"Card " + column.cards.length,
                description: t("general/empty"),
              };
              if (column) {
                column.cards.push(card);
              }
              props.refreshBoard(board);
            }}
          >
            <CardPlus></CardPlus>
          </IconButton>
          <IconButton
            onClick={() => {
              board.columns = board.columns.filter((l) => column.id !== l.id);
              props.refreshBoard(board);
            }}
          >
            <Close></Close>
          </IconButton>
        </Box>
      )}
    </Box>
  );
}
Example #19
Source File: AsyncSelect.tsx    From one-platform with MIT License 5 votes vote down vote up
AsyncSelect = ({
  render,
  onSelect,
  customFilter,
  onTypeaheadInputChanged,
  ...selectProps
}: Props): JSX.Element => {
  const [isOpen, setIsOpen] = useToggle();
  const [options, setOptions] = useState<ReactElement<any, string | JSXElementConstructor<any>>[]>(
    []
  );

  const [typeAhead, setTypeAhead] = useState('');

  useEffect(() => {
    if (!isOpen) {
      setTypeAhead('');
      setOptions([]);
      return;
    }

    setOptions(LOADING);
    render(typeAhead)
      .then((loadedOptions) => {
        setOptions(loadedOptions);
      })
      .catch(() => {
        setOptions([
          <SelectOption
            key="option-error"
            value="Failed to fetch request"
            isPlaceholder
            isDisabled
          />,
        ]);
      });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [typeAhead, isOpen]);

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const onPfeSelect = (...args: any) => {
    // eslint-disable-next-line prefer-spread
    onSelect?.apply(null, args);
    setIsOpen.off();
  };

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const onPfeTypeAheadChange = (value: string) => {
    setTypeAhead(value);
    // eslint-disable-next-line prefer-spread
    if (onTypeaheadInputChanged) onTypeaheadInputChanged(value);
  };

  const onFilter = (a: ChangeEvent<HTMLInputElement> | null, value: string) => {
    if (!value) {
      return options;
    }

    if (!customFilter) return options;

    return options.filter((child) => customFilter(child));
  };

  return (
    <PfeSelect
      {...selectProps}
      onSelect={onPfeSelect}
      isOpen={isOpen}
      onToggle={setIsOpen.toggle}
      onTypeaheadInputChanged={onPfeTypeAheadChange}
      onFilter={customFilter && onFilter}
    >
      {options}
    </PfeSelect>
  );
}
Example #20
Source File: Drawer.tsx    From Demae with MIT License 5 votes vote down vote up
_Drawer = ({ open, anchor, onClose, children }: { open: boolean, anchor: Anchor, onClose: () => void, children: any }) => {
	const classes = useStyles();

	const [state, setState] = React.useState({
		top: false,
		left: false,
		bottom: false,
		right: false,
	});

	const toggleDrawer = (anchor: Anchor, open: boolean) => (
		event: React.KeyboardEvent | React.MouseEvent,
	) => {
		if (
			event.type === 'keydown' &&
			((event as React.KeyboardEvent).key === 'Tab' ||
				(event as React.KeyboardEvent).key === 'Shift')
		) {
			return;
		}

		setState({ ...state, [anchor]: open });
	};

	const Content = (anchor: Anchor) => (
		<div
			className={clsx(classes.list, {
				[classes.fullList]: anchor === 'top' || anchor === 'bottom',
			})}
			role="presentation"
			onClick={toggleDrawer(anchor, false)}
			onKeyDown={toggleDrawer(anchor, false)}
		>
			{children}
		</div>
	);

	return (
		<div>
			<Drawer anchor={anchor} open={open} onClose={onClose}>
				{Content(anchor)}
			</Drawer>
		</div>
	);
}
Example #21
Source File: index.tsx    From react_admin with MIT License 5 votes vote down vote up
Echarts: React.FC<Props> = () => {
  /**
   * 初始化数据
   */
  const [data, setData] = useState<any>()
  useEffect(() => {
    const arr = [820, 932, 901, 934, 1290, 1330, 1620]
    setData([...arr])
  }, [])
  /**
   * echarts配置项
   */
  const getOption = {
    title: {
      text: '名字\n很香',
      subtext: '副标题',
    },
    tooltip: {
      trigger: 'item',
    },
    legend: {
      data: ['星期'],
    },
    toolbox: {
      show: true,
      feature: {
        dataView: {
          show: true,
          readOnly: false,
        },
        magicType: {
          type: ['line', 'bar', 'stack', 'tiled'],
        },
        restore: {
          show: true,
        },
        saveAsImage: {
          show: true,
          type: 'jpg',
        },
      },
    },
    xAxis: {
      type: 'category',
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
      name: '星期几',
      position: 'bottom',
      nameLocation: 'end',
      nameTextStyle: {
        color: 'red',
        fontWeight: 'bold',
      },
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: '星期',
        data,
        type: 'bar',
        areaStyle: {},
      },
    ],
  }
  /**
   * 进行渲染
   */
  return (
    <ReactEcharts
      option={getOption}
      notMerge={true}
      lazyUpdate={true}
      theme={'theme_name'}
    />
  )
}
Example #22
Source File: StartUp.tsx    From 3Speak-app with GNU General Public License v3.0 5 votes vote down vote up
export function StartUp(props: any) {
  const [show, setShow] = useState(false)
  const [message, setMessage] = useState('')

  useEffect(() => {
    const load = async () => {
      const backendStatus = (await PromiseIpc.send('core.status', undefined as any)) as any
      if (backendStatus.ready === false) {
        setShow(true)
        const pid = setInterval(async () => {
          const status = (await PromiseIpc.send('core.status', undefined as any)) as any
          setMessage(status.start_progress.message)
        }, 25)
        PromiseIpc.send('core.ready', undefined as any).then((eda) => {
          setShow(false)
          clearInterval(pid)
        })
      }
    }

    void load()
  }, [])

  return (
    <div>
      <Modal show={show} backdrop={'static'} backdropClassName={'start-backdrop'}>
        <Modal.Header>
          <Modal.Title>App Starting Up</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <div style={{ textAlign: 'center' }}>
            <h1 style={{ paddingTop: '50px' }}>Loading</h1>
            <hr />
            <p style={{ fontSize: '15px' }}>{message}</p>
          </div>
        </Modal.Body>
      </Modal>
    </div>
  )
}
Example #23
Source File: CircleMenu.tsx    From react-circular-menu with Apache License 2.0 5 votes vote down vote up
CircleMenu: FC<Props> = ({
  rotationAngleInclusive = true,
  radius = 2,
  itemSize = 2,
  className,
  menuToggleElement,
  menuToggleClassName,
  onMenuToggle,
  ...props
}) => {
  const [menuActive, setMenuActive] = useState<boolean>(false);
  const childrenCount = Children.count(props.children);
  const itemCount = rotationAngleInclusive ? childrenCount - 1 : childrenCount;
  const toggleMenu = () => {
    const updatedMenuState = !menuActive;
    setMenuActive(updatedMenuState);
    onMenuToggle?.(updatedMenuState);
  };

  const menuToggle = menuToggleElement ? (
    cloneElement(menuToggleElement, {
      onClick: () => {
        menuToggleElement.props.onClick?.();
        toggleMenu();
      },
    })
  ) : (
    <CircleMenuToggle
      className={menuToggleClassName}
      menuActive={menuActive}
      size={itemSize}
      toggleMenu={toggleMenu}
    />
  );

  return (
    <Backdrop className={className} active={menuActive} onClick={toggleMenu}>
      {menuToggle}
      <StyledCircleMenuData>
        {Children.map(props.children, (child, index: number) => {
          // Calculating angle
          let angle = props.startAngle;
          let increment = 0;
          if (childrenCount > 1) {
            increment = Math.round(props.rotationAngle / itemCount);
          }
          angle += index * increment;

          return (
            <CircleMenuItem
              key={"cm-item-" + index}
              {...(child as ReactElement<CircleMenuItemProps>).props}
              size={itemSize}
              menuActive={menuActive}
              radius={radius}
              rotationAngle={angle}
            />
          );
        })}
      </StyledCircleMenuData>
    </Backdrop>
  );
}
Example #24
Source File: index.tsx    From react-native-gifted-charts with MIT License 5 votes vote down vote up
PieChart = (props: propTypes) => {
  const radius = props.radius || 120;
  const extraRadiusForFocused = props.extraRadiusForFocused || radius / 10;
  const pi = props.semiCircle ? Math.PI / 2 : Math.PI;
  const [selectedIndex, setSelectedIndex] = useState(-1);
  let startAngle = props.initialAngle || (props.semiCircle ? -pi : 0);
  let total = 0;
  props.data.forEach(item => {
    total += item.value;
  });
  if (selectedIndex !== 0) {
    let start = 0;
    for (let i = 0; i < selectedIndex; i++) {
      start += props.data[i].value;
    }
    startAngle += (2 * pi * start) / total;
  }
  return (
    <View
      style={{
        height: (radius + extraRadiusForFocused) * 2,
        width: (radius + extraRadiusForFocused) * 2,
      }}>
      {!(
        props.data.length <= 1 ||
        !props.focusOnPress ||
        selectedIndex === -1
      ) && (
        <View
          style={{
            position: 'absolute',
            top: -extraRadiusForFocused,
            left: -extraRadiusForFocused,
          }}>
          <PieChartMain
            {...props}
            data={[
              {
                value: props.data[selectedIndex].value,
                color:
                  props.data[selectedIndex].color || colors[selectedIndex % 9],
                strokeColor: props.data[selectedIndex].strokeColor || null,
                strokeWidth: props.data[selectedIndex].strokeWidth || null,
                gradientCenterColor:
                  props.data[selectedIndex].gradientCenterColor || null,
              },
              {
                value: total - props.data[selectedIndex].value,
                peripheral: true,
                strokeWidth: 0,
              },
            ]}
            radius={radius + extraRadiusForFocused}
            initialAngle={startAngle}
            showText={false}
            innerRadius={props.innerRadius || radius / 2.5}
          />
        </View>
      )}
      <View style={{position: 'absolute'}}>
        <PieChartMain
          {...props}
          selectedIndex={selectedIndex}
          setSelectedIndex={setSelectedIndex}
        />
      </View>
    </View>
  );
}
Example #25
Source File: useForm.tsx    From landy-react-template with MIT License 5 votes vote down vote up
useForm = (validate: any) => {
  const [values, setValues] = useState({});
  const [errors, setErrors] = useState({});
  const [shouldSubmit, setShouldSubmit] = useState(false);

  const openNotificationWithIcon = () => {
    notification["success"]({
      message: "Success",
      description: "Your message has been sent!",
    });
  };

  const handleSubmit = (event: React.ChangeEvent<HTMLFormElement>) => {
    event.preventDefault();
    setErrors(validate(values));
    // Your url for API
    const url = "";
    if (Object.keys(values).length === 3) {
      axios
        .post(url, {
          ...values,
        })
        .then(() => {
          setShouldSubmit(true);
        });
    }
  };

  useEffect(() => {
    if (Object.keys(errors).length === 0 && shouldSubmit) {
      setValues("");
      openNotificationWithIcon();
    }
  }, [errors, shouldSubmit]);

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    event.persist();
    setValues((values) => ({
      ...values,
      [event.target.name]: event.target.value,
    }));
    setErrors((errors) => ({ ...errors, [event.target.name]: "" }));
  };

  return {
    handleChange,
    handleSubmit,
    values,
    errors,
  };
}
Example #26
Source File: GridVideo.tsx    From ReactNative-UIKit with MIT License 5 votes vote down vote up
GridVideo: React.FC = () => {
  const max = useContext(MaxUidContext);
  const min = useContext(MinUidContext);
  const {rtcProps, styleProps} = useContext(PropsContext);
  const users =
    rtcProps.role === ClientRole.Audience
      ? [...max, ...min].filter((user) => user.uid !== 'local')
      : [...max, ...min];
  let onLayout = (e: any) => {
    setDim([
      e.nativeEvent.layout.width,
      e.nativeEvent.layout.height,
      e.nativeEvent.layout.width > e.nativeEvent.layout.height,
    ]);
  };
  const [dim, setDim]: [
    [number, number, boolean],
    Dispatch<SetStateAction<[number, number, boolean]>>,
  ] = useState([
    Dimensions.get('window').width,
    Dimensions.get('window').height,
    Dimensions.get('window').width > Dimensions.get('window').height,
  ]);
  const isDesktop = dim[0] > dim[1] + 100;
  let {matrix, dims} = useMemo(
    () => layout(users.length, isDesktop),
    [users.length, isDesktop],
  );
  return (
    <View style={style.full} onLayout={onLayout}>
      {matrix.map((r, ridx) => (
        <View style={style.gridRow} key={ridx}>
          {r.map((c, cidx) => (
            <View style={style.col} key={cidx}>
              <View
                style={{
                  ...style.gridVideoContainerInner,
                  ...(styleProps?.gridVideoView as object),
                }}>
                {rtcProps.role === ClientRole.Audience &&
                users[ridx * dims.c + cidx].uid === 'local' ? null : (
                  <MaxVideoView
                    user={users[ridx * dims.c + cidx]}
                    key={users[ridx * dims.c + cidx].uid}
                  />
                )}
              </View>
            </View>
          ))}
        </View>
      ))}
    </View>
  );
}