react#useRef JavaScript Examples

The following examples show how to use react#useRef. 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: deck-mode-normal.jsx    From MDXP with MIT License 6 votes vote down vote up
NormalMode = ({
  children,
  keyboardTarget,
  touchTarget,
  slideNavigation,
  modeNavigation
}) => {
  const element = useRef();
  const keyboardReference = keyboardTarget || element;
  const touchReference = touchTarget || element;
  useSetMode(deckModes.NORMAL);

  return (
    <div ref={element} tabIndex={-1} style={{width: '100%', height: '100%'}}>
      <Routing>
        <DeckState>
          <Extracted />
          <Slide>{children}</Slide>
          <Navigation
            keyboardReference={keyboardReference}
            touchReference={touchReference}
            slideNavigation={slideNavigation}
            modeNavigation={modeNavigation}
          />
        </DeckState>
      </Routing>
    </div>
  );
}
Example #2
Source File: index.js    From uniswap-v1-frontend with GNU General Public License v3.0 6 votes vote down vote up
export default function Identicon() {
  const ref = useRef()

  const { account } = useWeb3React()

  useEffect(() => {
    if (account && ref.current) {
      ref.current.innerHTML = ''
      ref.current.appendChild(Jazzicon(16, parseInt(account.slice(2, 10), 16)))
    }
  }, [account])

  return <StyledIdenticon ref={ref} />
}
Example #3
Source File: index.js    From acy-dex-interface with MIT License 6 votes vote down vote up
SearchField = ({ setKeyword, showSearch, setShowSearch }) => {
  const inputRef = useRef();

  let renderComponent;
  if (showSearch) {
    renderComponent = <div style={{ display: "flex", alignItems: "center", backgroundColor: "#191b20", margin: "0 -16px 0 0", borderRadius: "4px" }}>
      <input
        ref={inputRef}
        autoFocus
        style={{ display: showSearch ? "block" : "none", width: "100%", backgroundColor: "transparent", border: "1px solid #1c9965", borderRadius: "30px", outline: 0, paddingLeft: "0.4rem" }}
        onChange={e => { setKeyword(e.target.value) }}
        onKeyPress={e => { if (e.key === "Enter") setKeyword(e.target.value); inputRef.current.value = e.target.value }}
      />
      <Icon type="close"
        className={styles.hoverToWhite}
        style={{ justifyContent: "end", marginLeft: "0.7rem", marginRight: "0.2rem", fontSize: "0.9rem" }}
        onClick={() => {
          setKeyword("");
          inputRef.current.value = "";
          setShowSearch(false);
        }} />
    </div>;
  } else {
    renderComponent = <>
      Pool
      <Icon
        type="search"
        className={styles.hoverToWhite}
        style={{ backgroundColor: "transparent", color: "white", marginLeft: "1rem" }}
        onClick={() => { setShowSearch(true); console.log(showSearch) }}
      />
    </>;
  }
  return renderComponent;
}
Example #4
Source File: useSticky.js    From Website2020 with MIT License 6 votes vote down vote up
function useSticky() {
  const [isSticky, setSticky] = useState(false)
  const element = useRef(null)

  const handleScroll = () => {
    window.scrollY > element.current.getBoundingClientRect().bottom
      ? setSticky(true)
      : setSticky(false)
  }

  // This function handle the scroll performance issue
  const debounce = (func, wait = 20, immediate = true) => {
    let timeOut
    return () => {
      let context = this,
        args = arguments
      const later = () => {
        timeOut = null
        if (!immediate) func.apply(context, args)
      }
      const callNow = immediate && !timeOut
      clearTimeout(timeOut)
      timeOut = setTimeout(later, wait)
      if (callNow) func.apply(context, args)
    }
  }

  useEffect(() => {
    window.addEventListener("scroll", debounce(handleScroll))
    return () => {
      window.removeEventListener("scroll", () => handleScroll)
    }
  }, [debounce, handleScroll])

  return { isSticky, element }
}
Example #5
Source File: SearchFilter.js    From Elemento with MIT License 6 votes vote down vote up
SearchFilter = () => {
  const elementContext = useContext(ElementContext);
  const text = useRef("");

  const { filtered, searchElements } = elementContext;

  useEffect(() => {
    if (filtered === null) {
      text.current = "";
    }
  });

  const onChange = (e) => {
    if (text.current.value !== "") {
      searchElements(e.target.value);
    }
  };
  return (
    <div className="searcharea">

    <form className="customSearch">
      <input type={text} className="input"  placeholder="Search Navbar,Footer etc." onChange={onChange}/>
        </form>
    </div>
  );
}
Example #6
Source File: CustomSnackbarProvider.component.js    From akashlytics-deploy with GNU General Public License v3.0 6 votes vote down vote up
CustomSnackbarProvider = ({ children }) => {
  const notistackRef = useRef();
  const classes = useStyles();
  const onClickDismiss = (key) => () => {
    notistackRef.current.closeSnackbar(key);
  };

  return (
    <SnackbarProvider
      maxSnack={3}
      anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
      ref={notistackRef}
      classes={{
        containerRoot: classes.root,
        variantSuccess: classes.success,
        variantError: classes.error,
        variantWarning: classes.warning,
        variantInfo: classes.info
      }}
      hideIconVariant
      action={(key) => (
        <Box width="2rem">
          <IconButton onClick={onClickDismiss(key)} size="small" className={classes.action}>
            <CloseIcon fontSize="small" />
          </IconButton>
        </Box>
      )}
    >
      {children}
    </SnackbarProvider>
  );
}
Example #7
Source File: Search.js    From Next.js-e-commerce-online-store with MIT License 6 votes vote down vote up
export default function Search() { 
  const router = useRouter()
  const [ searchValue, setSearchValue ] = useState('')
  const inputRef = useRef(null)

  useEffect(() => {
    if (location.pathname.includes('search')) {
      inputRef.current.value = location.pathname.substr(location.pathname.lastIndexOf('/') + 1)
    } else {
      inputRef.current.value = ''
    }
  }, [])

  const search = e => {
    e.preventDefault()
    if (searchValue !== '') {
      router.push(`/search/${searchValue.trim()}`)
    } else { return null }
  }

  return (
    <form id="formSearchBar" onSubmit={search}>
      <input 
        aria-label="Search graph" 
        type="search" 
        name="search" 
        ref={inputRef} 
        onChange={e => setSearchValue(String(e.target.value))}
      />
      <button type="submit" value="submit" form="formSearchBar" aria-label="Search button">
        <FontAwesomeIcon icon={faSearch} />
      </button>
    </form>
  )
}
Example #8
Source File: hooks.js    From react-firechat with MIT License 6 votes vote down vote up
export function useFirestoreQuery(query) {
  const [docs, setDocs] = useState([]);

  // Store current query in ref
  const queryRef = useRef(query);

  // Compare current query with the previous one
  useEffect(() => {
    // Use Firestore built-in 'isEqual' method
    // to compare queries
    if (!queryRef?.curent?.isEqual(query)) {
      queryRef.current = query;
    }
  });

  // Re-run data listener only if query has changed
  useEffect(() => {
    if (!queryRef.current) {
      return null;
    }

    // Subscribe to query with onSnapshot
    const unsubscribe = queryRef.current.onSnapshot(querySnapshot => {
      // Get all documents from collection - with IDs
      const data = querySnapshot.docs.map(doc => ({
        ...doc.data(),
        id: doc.id,
      }));
      // Update state
      setDocs(data);
    });

    // Detach listener
    return unsubscribe;
  }, [queryRef]);

  return docs;
}
Example #9
Source File: Popover.js    From react-trello with MIT License 6 votes vote down vote up
Popover = ({ title = '', children = null, onClickOutside = () => null, offset = {}}) => {
  const popover = useRef(null);

  useClickOutsideEffect(popover, onClickOutside);

  return (
    <div
      ref={popover}
      className="popover"
      style={{
        marginTop: `${offset?.top ?? 0}px`,
        marginLeft: `${offset?.left ?? 0}px`
      }}
    >
      {
        title ? (
          <>
            <div className="popover-header">
              <h4>{title}</h4>
            </div>
            <hr className="divider" />
          </>
        ) : null
      }
      {children}
    </div>
  );
}
Example #10
Source File: index.js    From react-ui-components with MIT License 6 votes vote down vote up
Drawer = (props) => {
    const drawer = useRef();
    let className = {
        name: 'rui-drawer',
        position: props.position ? props.position : 'left',
        dark: props.dark && !props.light ? 'dark' : ''
    }

    const handleClick = (e) => {
        if (drawer.current && drawer.current.contains(e.target)) return;
        props.onClose()
    }

    useEffect(() => {
        document.addEventListener('mousedown', handleClick, true);

        return(() => {
            document.removeEventListener("mousedown", handleClick, true);
        })
    }, [])

    return (
        <CSSTransition
            in={props.drawer}
            timeout={300}
            classNames={`rui-drawer-${props.position ? props.position : 'left'}`}
            unmountOnExit>
            <div className="rui-drawer-overlay">
                <div ref={drawer}
                    style={{ width: props.width ? props.width : 280 }}
                    className={strinfigyClassObject(className)}>
                    {props.children}
                </div>
            </div>
        </CSSTransition>
    )
}
Example #11
Source File: Login.js    From connect-4-online-multiplayer with MIT License 6 votes vote down vote up
export default function Login() {
  const iRef = useRef();
  const setUser = useContext(DispatchUserContext);
  function handleSubmit(e) {
    e.preventDefault();
    setUser({ id: v4(), name: iRef.current.value });
  }

  return (
    <Container maxWidth="sm">
      <Box textAlign="center" pt={4}>
        <form onSubmit={handleSubmit}>
          {/* <label>Name:</label> */}
          <TextField
            id="outlined-basic"
            label="Enter your name"
            variant="outlined"
            inputRef={iRef}
            required
          />
          <Box py={4}>
            <Button type="submit" variant="contained" color="primary">
              Submit
            </Button>
          </Box>
        </form>
      </Box>
    </Container>
  );
}
Example #12
Source File: DownloadVideo.js    From video-journal-for-teams-fe with MIT License 6 votes vote down vote up
export function DownloadVideo({ videoUrl }) {
	const downloadRef = useRef(null);

	function download() {
		downloadRef.current.click();
	}

	return (
		<>
			<a ref={downloadRef} href={videoUrl} download="alpacavid.webm" hidden>
				Download Video
			</a>
			<Button onClick={download} style={{ margin: "8px" }} icon="download">
				<span>Download Video</span>
			</Button>
		</>
	);
}
Example #13
Source File: index.js    From bluezone-app with GNU General Public License v3.0 6 votes vote down vote up
FadeInView = (props) => {
    const fadeAnim = useRef(new Animated.Value(0)).current  // Initial value for opacity: 0

    React.useEffect(() => {
        Animated.timing(
            fadeAnim,
            {
                toValue: 1,
                duration: 10000,
            }
        ).start();
    }, [fadeAnim])

    return (
        <Animated.View                 // Special animatable View
            style={{
                ...props.style,
                opacity: fadeAnim,         // Bind opacity to animated value
            }}
        >
            {props.children}
        </Animated.View>
    );
}
Example #14
Source File: Map.jsx    From Corona-tracker with MIT License 6 votes vote down vote up
function Map() {
  const classes = useStyles();

  const [map, setMap] = useState(null);
  const mapContainer = useRef(null);

  useEffect(() => {
    mapboxgl.accessToken = mapboxToken;

    const initializeMap = () => {
      const initMap = new mapboxgl.Map({
        container: mapContainer.current,
        style: 'mapbox://styles/mapbox/dark-v9', // stylesheet location
        center: [-73.935242, 43.2994],
        zoom: 2,
      });

      initMap.on('load', () => {
        setMap(initMap);
        initMap.resize();
      });
    };

    if (!map) initializeMap();
  }, [map]);

  return (
    <div className={classes.mapContainer}>
      <h4>Check out the Map!</h4>
      <h4>...COMING SOON...</h4>
      <div
        ref={el => {
          mapContainer.current = el;
        }}
        className={classes.root}
      />
    </div>
  );
}
Example #15
Source File: mobile-menu.js    From website with Apache License 2.0 6 votes vote down vote up
MobileMenu = ({ expanded, topNavigation, subNavigation, hide }) => {
  const [menuHeight, setMenuHeight] = useState({ initial: 0, current: 0 })
  const menuRef = useRef()

  // Set initial menu height value to reset later.
  useEffect(() => {
    if (expanded) {
      setMenuHeight({ ...menuHeight, initial: menuRef.current.offsetHeight })
      menuRef.current.focus()
    }
  }, [expanded])

  return (
    <div
      ref={menuRef}
      className={classNames(mobileMenuStyle.mobileMenu, {
        [mobileMenuStyle.mobileMenuExpanded]: expanded,
      })}
      tabIndex="-1"
      style={{
        minHeight: `${menuHeight.current}px`,
      }}
    >
      <HeaderNavigation
        topNavigation={topNavigation}
        subNavigation={subNavigation}
        isMobile
        hide={hide}
      />
      <div className={mobileMenuStyle.mobilePointer} />
    </div>
  )
}
Example #16
Source File: Button.js    From ponce-tournois-mario-kart with MIT License 6 votes vote down vote up
function Button({ children, loading, disabled, primary = true, ...props }) {
    const { errors } = useFormContext();
    const [width, setWidth] = useState(0);
    const [height, setHeight] = useState(0);
    const ref = useRef(null);

    useEffect(() => {
        if (ref.current && ref.current.getBoundingClientRect().width) {
            setWidth(ref.current.getBoundingClientRect().width);
        }
        if (ref.current && ref.current.getBoundingClientRect().height) {
            setHeight(ref.current.getBoundingClientRect().height);
        }
    }, [children]);

    return (
        <button
            {...props}
            ref={ref}
            style={
                width && height
                    ? {
                          width: `${width}px`,
                          height: `${height}px`,
                      }
                    : {}
            }
            disabled={
                primary
                    ? disabled || Object.entries(errors).length > 0 || loading
                    : disabled || loading
            }
        >
            {loading ? <Loader /> : children}
        </button>
    );
}
Example #17
Source File: slide-in-slide.jsx    From MDXP with MIT License 5 votes vote down vote up
SlideInSlide = ({children, sx = {}}) => {
  const [wrapper, wrapperWidth, wrapperHeight] = useResizeObserver();
  const scaleElement = useRef();

  useLayoutEffect(() => {
    if (wrapperWidth && wrapperHeight && scaleElement.current) {
      const scale = Math.min(
        wrapperWidth / scaleElement.current.offsetWidth,
        wrapperHeight / scaleElement.current.offsetHeight
      );
      scaleElement.current.style = `transform: scale(${scale})`;
    }
  }, [wrapperWidth, wrapperHeight, scaleElement]);

  return (
    <div
      sx={{
        width: '100%',
        paddingBottom: '56.25%',
        height: '0',
        position: 'relative'
      }}
    >
      <div
        ref={wrapper}
        sx={{
          position: 'absolute',
          top: 0,
          bottom: 0,
          left: 0,
          right: 0,
          overflow: 'hidden'
        }}
      >
        <div
          ref={scaleElement}
          sx={{
            boxSizing: 'border-box',
            position: 'absolute',
            overflow: 'hidden',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            color: 'text',
            bg: 'white',
            width: '960px',
            height: '540px',
            transformOrigin: '0 0',
            '& p': {textAlign: 'center', mt: 0},
            '& h1': {mb: 0},
            ...sx
          }}
        >
          {children}
        </div>
      </div>
    </div>
  );
}
Example #18
Source File: miniheader.js    From about-1hive with GNU General Public License v3.0 5 votes vote down vote up
Header = props => {
  const node = useRef()
  const [darkMode, toggleDarkMode] = useDarkMode()

  const button = useRef()
  const [isMenuOpen, updateIsMenuOpen] = useState(false)

  const isMobile = useMediaQuery('(max-width: 960px)')

  return (
    <StyledHeader open={isMenuOpen}>
      <Row>
        <StyledNavTitleWrapper>
          <StyledHomeLink
            to="/"
            style={{
              textDecoration: `none`
            }}
          >
            <StyledUni />
          </StyledHomeLink>
          {props.path && props.path !== '/' && props.path !== '' && (
            <>
              <StyledNavTitle to={'/' + props.path.split('/')[1]}>
                {props.path.length > 20 ? 'Docs /' : '1hive Docs /'}
              </StyledNavTitle>
              <StyledNavTitle to={'/docs/' + props.path.split('/')[2]}>
                {props.path.split('/')[2].replace(/(^|\s)\S/g, function(t) {
                  return t.toUpperCase()
                })}
              </StyledNavTitle>
              <StyledNavTitle to={'/docs/' + props.path.split('/')[2] + '/' + props.path.split('/')[3]}>
                {props.path.split('/')[3] &&
                  '/ ' +
                    props.path
                      .split('/')[3]
                      .replace(/\d+-/g, '')
                      .replace(/-/g, ' ')
                      .replace(/(^|\s)\S/g, function(t) {
                        return t.toUpperCase()
                      })}
              </StyledNavTitle>{' '}
            </>
          )}
        </StyledNavTitleWrapper>
        <MenuToggle ref={button} open={isMenuOpen} onClick={() => updateIsMenuOpen(!isMenuOpen)}>
          {isMenuOpen ? <StyledCloseIcon /> : <StyledMenuIcon />}
        </MenuToggle>
        <StyledNav ref={node} open={isMenuOpen}>
          {!isMobile && <Search {...props} />}
          {isMobile }
          <StyledButton type="button" onClick={toggleDarkMode}>
            {darkMode ? <Sun size={20} /> : <Moon size={20} />}
          </StyledButton>
          <StyledButton fill>
            <a href="https://discord.gg/NTDBRNz">
              <Discord />
            </a>
          </StyledButton>
          <StyledButton fill>
            <a href="https://github.com/1hive">
              <Github width={20} />
            </a>
          </StyledButton>
          <StyledButton type="button">
            <Link to="/">
              <Home size={20} />{' '}
            </Link>
          </StyledButton>
        </StyledNav>
      </Row>
      <MobileSearchWrapper>
        <Search {...props} />
      </MobileSearchWrapper>
    </StyledHeader>
  )
}
Example #19
Source File: index.js    From tulip-frontend with GNU Affero General Public License v3.0 5 votes vote down vote up
Approve = props => {
  const {
    _web3ReactContext: { chainId },
  } = useWallet()
  const [visible, setVisible] = useState(false)
  const [txHash, setTxHash] = useState('')
  const opener = useRef()
  const balanceToEth = props.amount.balance
  const approve = useApprove(props.token, balanceToEth, chainId)
  const network = getNetworkConfig(chainId)

  const transactionTime = new Date()
  transactionTime.setSeconds(transactionTime.getSeconds() + 8)

  const handleApprove = () => {
    approve()
      .then(x => {
        if (x) {
          setVisible(true)
          setTxHash(x.hash)
          x.wait()
            .then(() => {
              setVisible(false)
            })
            .catch(err => {
              props.onError(err)
            })
        }
      })
      .catch(err => {
        props.onError(err)
      })
  }

  return (
    <>
      <Button
        css={`
          background: linear-gradient(90deg, #aaf5d4, #7ce0d6);
        `}
        label="Approve"
        wide
        onClick={handleApprove}
        ref={opener}
      />
      <TransactionProgress
        transactionHashUrl={network.txUrl + txHash}
        progress={1}
        visible={visible}
        endTime={transactionTime}
        onClose={() => setVisible(false)}
        opener={opener}
        slow={false}
      />
    </>
  )
}
Example #20
Source File: _Helpers.js    From acy-dex-interface with MIT License 5 votes vote down vote up
export function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}
Example #21
Source File: useSelector.js    From Path-Finding-Visualizer with MIT License 5 votes vote down vote up
function useSelectorWithStoreAndSubscription(selector, equalityFn, store, contextSub) {
  var _useReducer = useReducer(function (s) {
    return s + 1;
  }, 0),
      forceRender = _useReducer[1];

  var subscription = useMemo(function () {
    return new Subscription(store, contextSub);
  }, [store, contextSub]);
  var latestSubscriptionCallbackError = useRef();
  var latestSelector = useRef();
  var latestSelectedState = useRef();
  var selectedState;

  try {
    if (selector !== latestSelector.current || latestSubscriptionCallbackError.current) {
      selectedState = selector(store.getState());
    } else {
      selectedState = latestSelectedState.current;
    }
  } catch (err) {
    if (latestSubscriptionCallbackError.current) {
      err.message += "\nThe error may be correlated with this previous error:\n" + latestSubscriptionCallbackError.current.stack + "\n\n";
    }

    throw err;
  }

  useIsomorphicLayoutEffect(function () {
    latestSelector.current = selector;
    latestSelectedState.current = selectedState;
    latestSubscriptionCallbackError.current = undefined;
  });
  useIsomorphicLayoutEffect(function () {
    function checkForUpdates() {
      try {
        var newSelectedState = latestSelector.current(store.getState());

        if (equalityFn(newSelectedState, latestSelectedState.current)) {
          return;
        }

        latestSelectedState.current = newSelectedState;
      } catch (err) {
        // we ignore all errors here, since when the component
        // is re-rendered, the selectors are called again, and
        // will throw again, if neither props nor store state
        // changed
        latestSubscriptionCallbackError.current = err;
      }

      forceRender({});
    }

    subscription.onStateChange = checkForUpdates;
    subscription.trySubscribe();
    checkForUpdates();
    return function () {
      return subscription.tryUnsubscribe();
    };
  }, [store, subscription]);
  return selectedState;
}
Example #22
Source File: NotificationArea.js    From ActiveLearningStudio-react-client with GNU Affero General Public License v3.0 5 votes vote down vote up
NotificationArea = (props) => {
  const { content, type } = props;
  const dispatch = useDispatch();
  const notificationText = useRef();
  let userNameImg = '';
  let firstLetter = '';
  let lastLetter = '';

  if (content.notifiable) {
    if (content.notifiable.first_name) {
      [firstLetter] = content.notifiable.first_name;
    }
    if (content.notifiable.last_name) {
      [lastLetter] = content.notifiable.last_name;
    }
    userNameImg = firstLetter + lastLetter;
  }
  useEffect(() => {
    if (notificationText.current) {
      notificationText.current.innerHTML = content.data?.message;
    }
  }, [content.data]);

  return (
    <>
      {content.data?.message && (
        <div className="notification-area">
          {content.type.includes('ProjectExportNotification') ? (
            <div className="user-detail">
              {/* <img src={flashCards} alt="" /> */}
              <div className="user-icons">{userNameImg.toUpperCase()}</div>
              <p>
                Project &nbsp;
                <b>{content.data.project}</b>
                &nbsp; has been exported successfully.
                <br />
                Please&nbsp;
                <a
                  target="_blank"
                  // eslint-disable-next-line max-len
                  href={`${window.__RUNTIME_CONFIG__.REACT_APP_API_URL}/users/notifications/${content.id}/download-export?token=${localStorage.auth_token}`}
                  rel="noreferrer"
                >
                  Click here
                </a>
                &nbsp; to download the exported file
              </p>
            </div>
          ) : (
            <div className="user-detail">
              {/* <img src={flashCards} alt="" /> */}
              <div className="user-icons">{userNameImg.toUpperCase()}</div>
              <p>{content.data?.message}</p>
            </div>
          )}

          <div className="settings-notification">
            {type === 'header' && (
              <Dropdown className="pull-right playlist-dropdown check">
                <Dropdown.Toggle className="playlist-dropdown-btn">
                  <FontAwesomeIcon icon="ellipsis-v" />
                </Dropdown.Toggle>
                <Dropdown.Menu>
                  <Dropdown.Item onClick={() => dispatch(deleteNotification(content.id))}>
                    <FontAwesomeIcon icon="times-circle" className="mr-2" />
                    Delete
                  </Dropdown.Item>
                </Dropdown.Menu>
              </Dropdown>
            )}
            <div className="timer">{content.created_at}</div>
          </div>
        </div>
      )}
    </>
  );
}
Example #23
Source File: DeploymentNameModal.js    From akashlytics-deploy with GNU General Public License v3.0 5 votes vote down vote up
DeploymentNameModal = ({ dseq, onClose, onSaved, getDeploymentName }) => {
  const classes = useStyles();
  const formRef = useRef();
  const { enqueueSnackbar } = useSnackbar();
  const { handleSubmit, control, setValue } = useForm({
    defaultValues: {
      name: ""
    }
  });

  useEffect(() => {
    if (dseq) {
      const name = getDeploymentName(dseq);
      setValue("name", name || "");
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dseq, getDeploymentName]);

  const onSaveClick = (event) => {
    event.preventDefault();
    formRef.current.dispatchEvent(new Event("submit", { cancelable: true, bubbles: true }));
  };

  function onSubmit({ name }) {
    updateDeploymentLocalData(dseq, { name: name });

    enqueueSnackbar(<Snackbar title="Success!" iconVariant="success" />, { variant: "success", autoHideDuration: 1000 });

    onSaved();
  }

  return (
    <Dialog open={!!dseq} onClose={onClose} maxWidth="xs" fullWidth>
      <DialogTitle>Change Deployment Name {dseq ? `(${dseq})` : ""}</DialogTitle>
      <DialogContent dividers className={classes.dialogContent}>
        <form onSubmit={handleSubmit(onSubmit)} ref={formRef}>
          <FormControl fullWidth>
            <Controller
              control={control}
              name="name"
              render={({ field }) => {
                return <TextField {...field} autoFocus type="text" variant="outlined" label="Name" />;
              }}
            />
          </FormControl>
        </form>
      </DialogContent>
      <DialogActions className={classes.dialogActions}>
        <Button onClick={onClose}>Close</Button>
        <Button variant="contained" color="primary" onClick={onSaveClick}>
          Save
        </Button>
      </DialogActions>
    </Dialog>
  );
}
Example #24
Source File: index.jsx    From vpp with MIT License 5 votes vote down vote up
HeaderSearch = props => {
  const {
    className,
    defaultValue,
    onVisibleChange,
    placeholder,
    open,
    defaultOpen,
    ...restProps
  } = props;
  const inputRef = useRef(null);
  const [value, setValue] = useMergeValue(defaultValue, {
    value: props.value,
    onChange: props.onChange,
  });
  const [searchMode, setSearchMode] = useMergeValue(defaultOpen || false, {
    value: props.open,
    onChange: onVisibleChange,
  });
  const inputClass = classNames(styles.input, {
    [styles.show]: searchMode,
  });
  return (
    <div
      className={classNames(className, styles.headerSearch)}
      onClick={() => {
        setSearchMode(true);

        if (searchMode && inputRef.current) {
          inputRef.current.focus();
        }
      }}
      onTransitionEnd={({ propertyName }) => {
        if (propertyName === 'width' && !searchMode) {
          if (onVisibleChange) {
            onVisibleChange(searchMode);
          }
        }
      }}
    >
      <SearchOutlined
        key="Icon"
        style={{
          cursor: 'pointer',
        }}
      />
      <AutoComplete
        key="AutoComplete"
        className={inputClass}
        value={value}
        style={{
          height: 28,
          marginTop: -6,
        }}
        options={restProps.options}
        onChange={setValue}
      >
        <Input
          ref={inputRef}
          defaultValue={defaultValue}
          aria-label={placeholder}
          placeholder={placeholder}
          onKeyDown={e => {
            if (e.key === 'Enter') {
              if (restProps.onSearch) {
                restProps.onSearch(value);
              }
            }
          }}
          onBlur={() => {
            setSearchMode(false);
          }}
        />
      </AutoComplete>
    </div>
  );
}
Example #25
Source File: CreateList.js    From TrelloClone with MIT License 5 votes vote down vote up
CreateList = () => {
  const [adding, setAdding] = useState(false);
  const [title, setTitle] = useState('');
  const dispatch = useDispatch();

  const formRef = useRef(null);
  useEffect(() => {
    formRef && formRef.current && formRef.current.scrollIntoView();
  }, [title]);

  const onSubmit = async (e) => {
    e.preventDefault();
    dispatch(addList({ title }));
    setTitle('');
  };

  return !adding ? (
    <div className='create-list-button'>
      <Button variant='contained' onClick={() => setAdding(true)}>
        + Add a list
      </Button>
    </div>
  ) : (
    <div ref={formRef} className='create-list-form'>
      <form onSubmit={(e) => onSubmit(e)}>
        <TextField
          variant='outlined'
          fullWidth
          margin='normal'
          required
          label='Enter list title'
          autoFocus
          value={title}
          onChange={(e) => setTitle(e.target.value)}
        />
        <div>
          <Button type='submit' variant='contained' color='primary'>
            Add List
          </Button>
          <Button
            onClick={() => {
              setAdding(false);
              setTitle('');
            }}
          >
            <CloseIcon />
          </Button>
        </div>
      </form>
    </div>
  );
}
Example #26
Source File: UploadButton.js    From viade_en1b with MIT License 5 votes vote down vote up
UploadButton = (props) => {

    const [state, setState] = useState({
        filename: "",
        numberOfFiles: 0
    });

    useEffect(() => {
        if (props.reset) { resetState(); }
    }, [props.reset]);

    const resetState = () => {
        setState({
            filename: "",
            numberOfFiles: 0
        });
    };
    const file = useRef()

    const checkFileIsGPX = (file) => {
        var parts = file.split(".");
        var ext = parts[parts.length - 1];
        switch (ext.toLowerCase()) {
            case "gpx":
                return true;
            default:
                return false;
        }
    };

    const handleSingleFileChanged = (e) => {
        props.onChange(e);
        if (file.current.files[0] !== undefined && checkFileIsGPX(file.current.files[0].name)) {
            let name = file.current.files[0].name;
            setState({ ...state, filename: name });
        }
        else {
            let name = "";
            setState({ ...state, filename: name });
        }

    };

    const handleMultipleFileChanged = (e) => {
        props.onChange(e);
        let number = file.current.files.length;
        setState({ ...state, numberOfFiles: number });
    };

    const uploadButton = (props.file)
        ?
        <Form.Group className={props.className}>
            <Form.Control ref={file} onChange={handleSingleFileChanged} id={props.id} type="file" accept=".gpx"></Form.Control>
            <Form.Label className="uploadLabel" htmlFor={props.id}>
                <p data-testid="upload-button-label">{state.filename !== "" ? state.filename : props.text}</p>
                <BsUpload></BsUpload>
            </Form.Label>
        </Form.Group>
        :
        (props.videos ?
            <Form.Group className={props.className}>
                <Form.Control multiple ref={file} onChange={handleMultipleFileChanged} id={props.id} type="file" accept="video/*"></Form.Control>
                <Form.Label className="uploadLabel" htmlFor={props.id}>
                    <p>{state.numberOfFiles !== 0 ? state.numberOfFiles + " files selected" : props.text}</p>
                    <BsUpload></BsUpload>
                </Form.Label>
            </Form.Group> :
            <Form.Group className={props.className}>
                <Form.Control multiple ref={file} onChange={handleMultipleFileChanged} id={props.id} type="file" accept="image/*"></Form.Control>
                <Form.Label className="uploadLabel" htmlFor={props.id}>
                    <p>{state.numberOfFiles !== 0 ? state.numberOfFiles + " files selected" : props.text}</p>
                    <BsUpload></BsUpload>
                </Form.Label>
            </Form.Group>
        )

    return (
        uploadButton
    );
}
Example #27
Source File: ProfileBackground.jsx    From ashteki with GNU Affero General Public License v3.0 5 votes vote down vote up
ProfileBackground = ({
    backgrounds,
    selectedBackground,
    customBackground,
    onBackgroundSelected
}) => {
    const { t } = useTranslation();
    const uploadRef = useRef();
    const [localCustomBg, setCustomBg] = useState(
        customBackground ? `/img/bgs/${customBackground}.png` : null
    );
    const [fileError, setFileError] = useState(null);

    return (
        <Panel title={t('Game Board Background')}>
            <Row>
                {backgrounds.map((background) => (
                    <Col
                        sm={4}
                        onClick={() => onBackgroundSelected(background.name, null)}
                        key={background.name}
                    >
                        <img
                            className={classNames('img-fluid', {
                                selected: selectedBackground === background.name
                            })}
                            src={background.imageUrl}
                        />
                        <span className='bg-label'>{background.label}</span>
                    </Col>
                ))}
                <Col sm={4}>
                    <img
                        className={classNames('img-fluid custom-bg', {
                            selected: selectedBackground === 'custom'
                        })}
                        src={localCustomBg}
                        onClick={() => uploadRef.current?.click()}
                    />
                    <Form.Control
                        name='avatar'
                        type='file'
                        accept='image/*'
                        hidden
                        onChange={(event) => {
                            if (
                                !event.currentTarget ||
                                !event.currentTarget.files ||
                                event.currentTarget.files.length === 0
                            ) {
                                return;
                            }

                            const file = event.currentTarget.files[0];

                            if (file.type !== 'image/png' && file.type !== 'image/jpeg') {
                                setFileError('File must be an image');
                                setCustomBg(null);
                            } else if (file.size / 1024 / 1024 > 5) {
                                setFileError('File must be less than 5MB');
                                setCustomBg(null);
                            } else {
                                setCustomBg(URL.createObjectURL(file));
                                onBackgroundSelected('custom', file);
                                setFileError(false);
                            }
                        }}
                        ref={uploadRef}
                    ></Form.Control>
                    {fileError && <span className='text-danger bg-error'>{fileError}</span>}
                    <span className='bg-label'>Custom</span>
                </Col>
            </Row>
        </Panel>
    );
}
Example #28
Source File: index.js    From react-ui-components with MIT License 5 votes vote down vote up
AvatarUploader = (props) => {
    const inputFile = useRef();
    const [avatar, setAvatar] = useState(props.avatar);
    const [inputKey, setInputKey] = useState(Date.now());

    let className = {
        name: 'rui-avatar-uploader',
        lifted: props.lifted ? 'lifted' : '',
        dark: props.dark ? 'dark' : '',
        borderType: props.borderType ? props.borderType : '', 
        className: props.className ? props.className : ''
    }

    const handlePreview = async (e) => {
        let file = e.target.files ? e.target.files[0] : null
        let b = await getBase64(file)
        setAvatar(b)
        props.onChange(b);
    }

    const handleDelete = (e) => {
        e.preventDefault();
        props.onClear()
        setAvatar('')
        setInputKey(Date.now())
    }

    return (
        <div className={strinfigyClassObject(className)}
            ref={props.avatarRef} 
            style={{
                ...props.style,
                backgroundImage: `url(${avatar})`
            }}>
            {!avatar ?
                <>
                    <label>{props.label ? props.label : props.label === null ? '' : 'upload avatar'}</label>
                    {props.placeholderImage ? props.placeholderImage :
                        <i className="rui-avatar-uploader-placeholder"><Account/></i>}
                </>
                : <Button 
                    light
                    icon={<Icon name="close"/>} 
                    className="ma-0"
                    onClick={handleDelete}/>
            }
            <input
                ref={inputFile}
                key={inputKey}
                accept="image/*"
                title={props.title ? props.title : 'Choose file'}
                onChange={handlePreview}
                type="file"/>
        </div>
    )
}
Example #29
Source File: PostVideoModal.js    From video-journal-for-teams-fe with MIT License 5 votes vote down vote up
PostVideoModal = ({toggleStreamPlayback, showModal, toggleModal, videoStream, user_id, promptId, uploadVideo}) => {
	const [videoData, setvideoData] = useState({
				title: "",
				description: "",
				owner_id: user_id,
				prompt_id: promptId,
			});

	const formRef = useRef(null);

	function handleFormInput(e) {
		setvideoData({ ...videoData, [e.target.name]: e.target.value });
	}

	const PostVideoMode = () => {
		if (videoStream && videoStream.playback) {
			return "playback"
		} else if (videoStream && !videoStream.playback && videoStream.raw && videoStream.raw[0] instanceof Blob === true) {
				return "upload"
			} else {
				return "recording"	
		}
	}

	const handleOk = (e) => {
		if (PostVideoMode() === "playback") {
			toggleStreamPlayback();
		} else if (PostVideoMode() === "upload") {
			formRef.current.getForm().validateFields((err, values) => {
				if (!err) {
					//No errors, begin upload
					uploadVideo({...videoData, raw: videoStream.raw});
					toggleModal();
				}
			});
		}
	}

	return (
		<Modal
			centered
			title="Post New Video"
			visible={showModal}
			bodyStyle={{ height: '10%' }}
			onOk={handleOk}
			onCancel={toggleModal}
			okButtonProps={{ form: "upload", htmlType: "submit", disabled: PostVideoMode() === "recording" ? true : false} }
			okText={PostVideoMode() !== "upload" ? "Continue" : "Upload"}
		>
			{PostVideoMode() === "recording" ? <RecordStream showModal={showModal}/> : null}
			{PostVideoMode() === "playback" ? <PlaybackStream /> : null}
			{PostVideoMode() === "upload" ? <UploadVideo ref={formRef} handleFormInput={handleFormInput}/> : null}
		</Modal>
	);
}