react#useEffect JavaScript Examples

The following examples show how to use react#useEffect. 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: auto-stepper.jsx    From MDXP with MIT License 6 votes vote down vote up
AutoStepper = ({start = 0, end = -1, time = 1000}) => {
  const {stepIndex, stepLength, preview} = useDeck();
  const {next} = useNavigation();

  time = parseInt(time);
  start = parseInt(start);
  if (start < 0) {
    start = stepLength + start;
  }

  end = parseInt(end);
  if (end <= 0) {
    end = stepLength + end;
  }

  useEffect(() => {
    if (!preview && document.hasFocus()) {
      if ((stepIndex >= start) && (stepIndex < end)) {
        const timer = setTimeout(() => {
          if ((stepIndex >= start) && (stepIndex <= end)) {
            next();
          }
        }, time);

        return () => clearTimeout(timer);
      }
    }
  });

  return null;
}
Example #2
Source File: Application.js    From about-1hive with GNU General Public License v3.0 6 votes vote down vote up
export function Updater() {
  const [, { updateDarkMode }] = useApplicationContext()
  useEffect(() => {
    const root = window.document.documentElement
    const initialColorValue = root.style.getPropertyValue('--initial-color-mode')
    if (initialColorValue === 'dark') {
      updateDarkMode(DARK_MODE_OPTION.DARK)
    } else {
      updateDarkMode(DARK_MODE_OPTION.DARK.LIGHT)
    }
  }, [])
  return null
}
Example #3
Source File: general-hooks.js    From payroll-app with GNU Affero General Public License v3.0 6 votes vote down vote up
export function useExternalContract(address, abi) {
  const api = useApi()
  const canInstantiate = Boolean(api && address && abi)
  const [contract, setContract] = useState(
    canInstantiate ? api.external(address, abi) : null
  )

  useEffect(() => {
    // We assume there is never any reason to set the contract back to null.
    if (canInstantiate && !contract) {
      setContract(api.external(address, abi))
    }
  }, [abi, address, api, canInstantiate, contract])

  return contract
}
Example #4
Source File: index.js    From tulip-frontend with GNU Affero General Public License v3.0 6 votes vote down vote up
SearchComponent = prop => {
  const [value, setValue] = useState('')
  useEffect(() => {
    prop.passSearch(value)
  }, [value])

  return (
    <React.Fragment>
      <SearchInput
        wide={prop.wide}
        value={value}
        onChange={setValue}
        placeholder={prop.placeholder}
      />
    </React.Fragment>
  )
}
Example #5
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 #6
Source File: world-map.js    From rsc-www with GNU Affero General Public License v3.0 6 votes vote down vote up
export default function WorldMapComponent() {
    useEffect(() => {
        const worldMap = new WorldMap({
            container: document.getElementById('rsc-world-map')
        });

        worldMap.init().catch((err) => {
            console.error(err);
        });
    }, []);

    return <div id="rsc-world-map" className="rsc-map" />;
}
Example #7
Source File: index.js    From react-json-view-compare with MIT License 6 votes vote down vote up
JsonCompare = props => {
  let { oldData, newData } = props;
  let [data, setMergeData] = useState([]);

  useEffect(() => {
    setMergeData(mergeData(oldData, newData));
  }, [oldData, newData]);

  return (
    <pre className="c-json-view">
      <p className="c-json-outter">{isArray(newData) ? '[' : '{'}</p>
      {data.map((item, index) => (
        <Tree key={index} {...item} />
      ))}
      <p className="c-json-outter">{isArray(newData) ? ']' : '}'}</p>
    </pre>
  );
}
Example #8
Source File: leagues.js    From poe-what-to-flip with MIT License 6 votes vote down vote up
useSelectedLeague = () => {
  const [leagues, setLeagues] = useState({});
  useEffect(() => {
    fetchLeagues().then(fetchedLeagues => {
      console.log(`Leagues: ${JSON.stringify(fetchedLeagues)}`);
      setLeagues(fetchedLeagues);
    });
  }, []);

  const [selectedMetaLeague, setSelectedMetaLeague] = useState("Temp SC");

  const [selectedLeague, setSelectedLeague] = useState();
  useEffect(() => {
    setSelectedLeague(leagues[selectedMetaLeague]);
  }, [leagues, selectedMetaLeague]);

  const metaLeagues = ["Temp SC", "Temp HC", "Standard", "Hardcore"];

  return {
    metaLeagues,
    selectedMetaLeague,
    selectedLeague,
    setSelectedMetaLeague,
  };
}
Example #9
Source File: index.js    From acy-dex-interface with MIT License 6 votes vote down vote up
export function useAllOrdersStats(chainId) {
  const query = gql(`{
    orderStat(id: "total") {
      openSwap
      openIncrease
      openDecrease
      executedSwap
      executedIncrease
      executedDecrease
      cancelledSwap
      cancelledIncrease
      cancelledDecrease
    }
  }`)

  const [res, setRes] = useState()

  useEffect(() => {
    getGmxGraphClient(chainId).query({ query }).then(setRes).catch(console.warn)
  }, [setRes, query, chainId])

  return res ? res.data.orderStat : null
}
Example #10
Source File: BookPage.js    From mern_library_nginx with MIT License 6 votes vote down vote up
BookPage = ({ match }) => {
   const dispatch = useDispatch();

   const bookDetails = useSelector((state) => state.bookDetails);
   const { loading, error, book } = bookDetails;

   useEffect(() => {
      dispatch(listBookDetails(match.params.id));
   }, [dispatch, match]);
   return (
      <>
         <Link className="btn btn-success my-3" to="/books">
            Go Back to My Books
         </Link>
         {loading ? (
            <Loader />
         ) : error ? (
            <Message variant="danger">{error}</Message>
         ) : (
            <Row>
               <Card className="my-3 p-3 rounded">
                  <Card.Header as="h2">
                     <strong>{book.title}</strong>
                  </Card.Header>
                  <Card.Body>
                     <Card.Subtitle className="mb-2 text-muted">
                        {book.subtitle}
                     </Card.Subtitle>
                     <Card.Text>{book.description}</Card.Text>

                     <Card.Text as="h6">ISBN {book.isbn}</Card.Text>
                     <Button variant="primary">{book.author}</Button>
                  </Card.Body>
               </Card>
            </Row>
         )}
      </>
   );
}
Example #11
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 #12
Source File: Provider.js    From Path-Finding-Visualizer with MIT License 6 votes vote down vote up
function Provider(_ref) {
  var store = _ref.store,
      context = _ref.context,
      children = _ref.children;
  var contextValue = useMemo(function () {
    var subscription = new Subscription(store);
    subscription.onStateChange = subscription.notifyNestedSubs;
    return {
      store: store,
      subscription: subscription
    };
  }, [store]);
  var previousState = useMemo(function () {
    return store.getState();
  }, [store]);
  useEffect(function () {
    var subscription = contextValue.subscription;
    subscription.trySubscribe();

    if (previousState !== store.getState()) {
      subscription.notifyNestedSubs();
    }

    return function () {
      subscription.tryUnsubscribe();
      subscription.onStateChange = null;
    };
  }, [contextValue, previousState]);
  var Context = context || ReactReduxContext;
  return React.createElement(Context.Provider, {
    value: contextValue
  }, children);
}
Example #13
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 #14
Source File: avatar.js    From website with BSD Zero Clause License 6 votes vote down vote up
Avatar = ({ img, clases }) => {
    const [imgProfesor, estImgProfesor] = useState(ImgUsuarioGenerico);

    useEffect(() => {
        estImgProfesor(img);
    }, [img])

    return (
        <img onError={() => estImgProfesor(ImgUsuarioGenerico)} alt='img-avatar' src={imgProfesor} className={clases} />
    )
}
Example #15
Source File: popup.jsx    From MDXP with MIT License 5 votes vote down vote up
Popup = ({children, time = 5000, step = 0}) => {
  const {stepIndex, mode} = useDeck();
  const [showPopup, setPopup] = useState(false);
  const style = (showPopup && (step === stepIndex) && (mode === deckModes.NORMAL)) ? {
    opacity: 1,
    transition: 'all 0.3s ease-out',
    width: '75%'
  } : {
    opacity: 0,
    transform: 'translate(-50%, 25%)',
    width: '75%'
  };

  useEffect(() => {
    if (step === stepIndex) {
      const timer = setTimeout(() => setPopup(true), time);
      return () => clearTimeout(timer);
    }

    setPopup(false);
  });

  return (
    <Place
      bottom="15px"
      sx={{
        ...style,
        bg: t => t.colors.MDXPYellow.slice(0, -1) + '22)',
        padding: 2,
        paddingLeft: t => t.space[3] - t.space[1],
        borderLeftWidth: t => t.space[1],
        borderLeftStyle: 'solid',
        borderLeftColor: 'MDXPYellow',
        borderRadius: '10px',
        '& p': {my: 0},
        fontSize: 'xsmall',
        lineHeight: '140%'
      }}
    >
      {children}
    </Place>
  );
}
Example #16
Source File: algoliaSearch.js    From about-1hive with GNU General Public License v3.0 5 votes vote down vote up
export default function Search(props) {
  // TEMP(onbjerg): Disable search until we are accepted into Docsearch.
  // When this happens we will have to reconfigure all of Docsearch-related
  // functionality, including the crawl-config.json
  return <></>

  const isV2 = props.path.slice(0, 8) === '/docs/honeyswap'

  // filter based on the version of the docs
  function handleResults(hits) {
    return hits.filter(hit => {
      if (hit.version) {
        return isV2 ? hit.version?.[0] === 'v2' : hit.version?.[0] === 'v1'
      } else {
        return isV2 ? hit.url.includes('v2') : hit.url.includes('v1')
      }
    })
  }

  // based on version, reset docsearch to use right facet filter
  useEffect(() => {
    if (window.docsearch) {
      try {
        window.docsearch({
          apiKey: '8962240e69e6d23a88432f501c115470',
          indexName: 'uniswap_v2_docs',
          appId: 'VZ0CVS8XCW',
          inputSelector: '.docsearch', // the selector of my search input
          transformData: handleResults
        })
      } catch (e) {
        console.log(e)
        console.log('Error loading algolia search')
      }
    }
  }, [])

  return (
    <SearchWrapper>
      <StyledForm>
        <StyledInput className="docsearch" placeholder="Search Docs..." />
        <ClearButton />
      </StyledForm>
    </SearchWrapper>
  )
}
Example #17
Source File: useAirdrop.js    From tulip-frontend with GNU Affero General Public License v3.0 5 votes vote down vote up
export function useClaim() {
  const [working, setWorking] = useState(false)
  const [txHash, setTxHash] = useState('')
  const {
    account,
    status,
    _web3ReactContext: { chainId },
  } = useWallet()
  const [unclaimed, setUnclaimed] = useState(0)
  const [available, setAvailable] = useState(0)
  const [balance, setBalance] = useState(0)
  const networks = getNetworkConfig(chainId)

  const contract = useContract(networks.StreamedAirdropper, StreamedAirdropper)
  const tokenb = useContract(networks.xCombToken, ERC20)

  const claim = useMemo(() => {
    if (!account || status === 'disconnected') {
      return
    }

    return async () => {
      const trnHash = await contract.withdrawTo(account)
      if (trnHash) {
        setTxHash(trnHash)
        setWorking(true)
        await trnHash.wait()
      }
      setWorking(false)
    }
  }, [account, contract, status])

  useEffect(() => {
    if (!account || status === 'disconnected') {
      setAvailable(0)
      return
    }
    let cancelled = false
    const fetchAvailable = async () => {
      try {
        const tokens = await contract.pendingTokens(account)
        if (!cancelled && tokens) {
          setAvailable(utils.formatUnits(tokens).substring(0, 9))
        }

        return tokens
      } catch (err) {
        console.error(`Could not fetch airdrop data `, err)
      }
    }

    const fetchUnclaimedData = async () => {
      try {
        const result = await contract.vestingUsers(account)
        if (result.length > 0) {
          const remainingTokens = result[0]
          const tokenBalance = await tokenb.balanceOf(account)
          setBalance(utils.formatUnits(tokenBalance).substring(0, 9))

          const rTokens = utils.formatUnits(remainingTokens)
          if (rTokens) {
            setUnclaimed(parseFloat(rTokens).toFixed(4))
          }
        }
      } catch (err) {
        console.log(err)
      }
    }

    fetchAvailable()
    fetchUnclaimedData()
    return () => {
      cancelled = true
    }
  }, [account, status, working])

  return [balance, claim, available, unclaimed, txHash, working]
}
Example #18
Source File: index.js    From uniswap-v1-frontend with GNU General Public License v3.0 5 votes vote down vote up
export default function Web3ReactManager({ children }) {
  const { t } = useTranslation()
  const { active } = useWeb3React()
  const { active: networkActive, error: networkError, activate: activateNetwork } = useWeb3React(NetworkContextName)

  // try to eagerly connect to an injected provider, if it exists and has granted access already
  const triedEager = useEagerConnect()

  // after eagerly trying injected, if the network connect ever isn't active or in an error state, activate itd
  // TODO think about not doing this at all
  useEffect(() => {
    if (triedEager && !networkActive && !networkError && !active) {
      activateNetwork(network)
    }
  }, [triedEager, networkActive, networkError, activateNetwork, active])

  // 'pause' the network connector if we're ever connected to an account and it's active
  useEffect(() => {
    if (active && networkActive) {
      network.pause()
    }
  }, [active, networkActive])

  // 'resume' the network connector if we're ever not connected to an account and it's active
  useEffect(() => {
    if (!active && networkActive) {
      network.resume()
    }
  }, [active, networkActive])

  // when there's no account connected, react to logins (broadly speaking) on the injected provider, if it exists
  useInactiveListener(!triedEager)

  // handle delayed loader state
  const [showLoader, setShowLoader] = useState(false)
  useEffect(() => {
    const timeout = setTimeout(() => {
      setShowLoader(true)
    }, 600)

    return () => {
      clearTimeout(timeout)
    }
  }, [])

  // on page load, do nothing until we've tried to connect to the injected connector
  if (!triedEager) {
    return null
  }

  // if the account context isn't active, and there's an error on the network context, it's an irrecoverable error
  if (!active && networkError) {
    return (
      <MessageWrapper>
        <Message>{t('unknownError')}</Message>
      </MessageWrapper>
    )
  }

  // if neither context is active, spin
  if (!active && !networkActive) {
    return showLoader ? (
      <MessageWrapper>
        <SpinnerWrapper src={Circle} />
      </MessageWrapper>
    ) : null
  }

  return children
}
Example #19
Source File: Greetings.jsx    From developer-portfolio with Apache License 2.0 5 votes vote down vote up
Greetings = () => {
	useEffect(() => {
		document.documentElement.scrollTop = 0;
		document.scrollingElement.scrollTop = 0;
	});
	return (
		<main>
			<div className="position-relative">
				<section className="section section-lg section-shaped pb-250">
					<div className="shape shape-style-1 bg-gradient-info">
						<span />
						<span />
						<span />
						<span />
						<span />
						<span />
						<span />
						<span />
						<span />
					</div>
					<Container className="py-lg-md d-flex">
						<div className="col px-0">
							<Row>
								<Col lg="6">
									<h1 className="display-3 text-white">
										{greetings.title + " "}
									</h1>
									<p className="lead text-white">
										{greetings.description}
									</p>
									<SocialLinks />
									<div className="btn-wrapper my-4">
										<Button
											className="btn-white btn-icon mb-3 mb-sm-0 ml-1"
											color="default"
											href={greetings.resumeLink}
										>
											<span className="btn-inner--icon mr-1">
												<i className="fa fa-file" />
											</span>
											<span className="btn-inner--text">
												See My Resume
											</span>
										</Button>
									</div>
								</Col>
								<Col lg="6">
									<GreetingLottie animationPath="/lottie/coding.json" />
								</Col>
							</Row>
						</div>
					</Container>
					{/* SVG separator */}
					<div className="separator separator-bottom separator-skew">
						<svg
							xmlns="http://www.w3.org/2000/svg"
							preserveAspectRatio="none"
							version="1.1"
							viewBox="0 0 2560 100"
							x="0"
							y="0"
						>
							<polygon
								className="fill-white"
								points="2560 0 2560 100 0 100"
							/>
						</svg>
					</div>
				</section>
				{/* 1st Hero Variation */}
			</div>
		</main>
	);
}
Example #20
Source File: drop-down.js    From rsc-www with GNU Affero General Public License v3.0 5 votes vote down vote up
export default function DropDown(props) {
    const [isVisible, setVisible] = useState(false);

    const [oldButton] = props.children;

    const button = React.cloneElement(oldButton, {
        onClick: () => setVisible(!isVisible)
    });

    useEffect(() => {
        window.addEventListener('mouseup', () => {
            setVisible(false);
        });
    }, []);

    return (
        <div className="rsc-drop-down">
            {button}
            <ul
                className="rsc-drop-down-links"
                style={{
                    display: isVisible ? 'block' : 'none'
                }}
            >
                {props.children.slice(1).map((a, i) => {
                    a = React.cloneElement(
                        a,
                        {
                            ...a.props,
                            className: (a.props.className || '') + ' rsc-link'
                        },
                        a.props.children
                    );

                    return (
                        <li key={i}>
                            <Link href={a.props.href}>{a}</Link>
                        </li>
                    );
                })}
            </ul>
        </div>
    );
}
Example #21
Source File: index.js    From acy-dex-interface with MIT License 5 votes vote down vote up
export function useAllPositions(chainId, library) {
  const count = 1000
  const query = gql(`{
    aggregatedTradeOpens(
      first: ${count}
    ) {
      account
      initialPosition{
        indexToken
        collateralToken
        isLong
        sizeDelta
      }
      increaseList {
        sizeDelta
      }
      decreaseList {
        sizeDelta
      }
    }
  }`)

  const [res, setRes] = useState()

  useEffect(() => {
    nissohGraphClient.query({ query }).then(setRes).catch(console.warn)
  }, [setRes, query])

  const key = res ? `allPositions${count}__` : false
  const { data: positions = [] } = useSWR(key, async () => {
    const provider = getProvider(library, chainId)
    const vaultAddress = getContract(chainId, "Vault")
    const contract = new ethers.Contract(vaultAddress, Vault.abi, provider)
    const ret = await Promise.all(res.data.aggregatedTradeOpens.map(async dataItem => {
      try {
        const { indexToken, collateralToken, isLong } = dataItem.initialPosition
        const positionData = await contract.getPosition(dataItem.account, collateralToken, indexToken, isLong)
        const position = {
          size: bigNumberify(positionData[0]),
          collateral: bigNumberify(positionData[1]),
          entryFundingRate: bigNumberify(positionData[3]),
          account: dataItem.account
        }
        position.fundingFee = await contract.getFundingFee(collateralToken, position.size, position.entryFundingRate)
        position.marginFee = position.size.div(1000)
        position.fee = position.fundingFee.add(position.marginFee)

        const THRESHOLD = 5000
        const collateralDiffPercent = position.fee.mul(10000).div(position.collateral)
        position.danger = collateralDiffPercent.gt(THRESHOLD)

        return position
      } catch (ex) {
        console.error(ex)
      }
    }))

    return ret.filter(Boolean)
  })

  return positions
}
Example #22
Source File: MobileNavigation.js    From bunk-manager-mern with MIT License 5 votes vote down vote up
MobileNavigation = () => {
  const classes = useStyles();
  const [value, setValue] = React.useState("Home");

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };
  useEffect(() => {
    if (window.location.pathname === "/" && value !== "Home") {
      setValue("Home");
    } else if (window.location.pathname === "/subject" && value !== "Subject") {
      setValue("Subject");
    } else if (
      window.location.pathname === "/semester" &&
      value !== "Semester"
    ) {
      setValue("Semester");
    } else if (window.location.pathname === "/about" && value !== "About") {
      setValue("About");
    }
  }, [value]);

  return (
    <React.Fragment>
      <AppBar position="fixed" color="primary" className={classes.appBar}>
        <BottomNavigation
          value={value}
          onChange={(event, newValue) => {
            setValue(newValue);
          }}
          showLabels
          className={classes.root}
        >
          <BottomNavigationAction
            component={Link}
            to="/"
            value="Home"
            icon={<HomeRoundedIcon />}
            label="Home"
          />
          <BottomNavigationAction
            component={Link}
            to="/subject"
            value="Subject"
            icon={<SubjectIcon />}
            label="Subject"
          />
          <BottomNavigationAction
            component={Link}
            to="/semester"
            value="Semester"
            icon={<SchoolRoundedIcon />}
            label="Semester"
          />
          <BottomNavigationAction
            component={Link}
            to="/about"
            value="About"
            icon={<MailOutlineRoundedIcon />}
            label="About"
          />
        </BottomNavigation>
      </AppBar>
    </React.Fragment>
  );
}
Example #23
Source File: TeamHeads.js    From Website2020 with MIT License 5 votes vote down vote up
function TeamHeads() {
    useEffect(() => {
        window.scrollTo(0, 0)
    });
    return (
        <>
            <div style={{ marginTop: "8rem", padding: "20px" }}>
                <Container>
                    <Row>
                        <Col>
                            <h2 className="text-center heading-main">OUR TEAM</h2>
                        </Col>
                    </Row>
                    <Row>
                        <Col lg="12" sm="12" className="description">
                            <img src={teamphoto} className="w-100 text-center"></img>
                            <p className="mb-4 mt-4">Over the past years, the team has witnessed a close collaboration between students from various departments coming and sharing ideas; creating a small yet strong network of people who are eagerly looking for a low-cost solution to large-scale problems.</p>
                            <p className="mb-3 ">Working long hours and brainstorming some complex problems leads to a very special bonding between the members of the teams. This leads to a lot of nicknames and some extremely fun gaming nights.</p>
                        </Col>
                    </Row>
                </Container>
            </div>
            <div className="section team-data text-center">
                <Container>
                    {
                        teamheads.teamData.map((section) => {
                            return (
                                <div>
                                    <Row className="justify-content-center">
                                        {section.items.map((teamMember) => {
                                            return (
                                                <Col lg="3" md="6" className="team text-center">
                                                    <div className="alignment">
                                                        <div className="member">
                                                            <div className="member-img">
                                                                <div className="overlay">
                                                                    <img src={require("assets/img/" + teamMember.image)}
                                                                        className="member-img img-fluid" alt="" />
                                                                </div>
                                                                <div className="social">
                                                                    <a href={teamMember.facebook} target='_blank'><i className="fa fa-facebook fa-2x" /></a>
                                                                    <a href={teamMember.linkedin} target='_blank'><i className="fa fa-linkedin fa-2x" /></a>
                                                                </div>
                                                            </div>
                                                            <div class="member-info">
                                                                <h4>{teamMember.name}</h4>
                                                                <span>{teamMember.subheading}</span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </Col>
                                            )
                                        })}
                                    </Row>
                                </div>
                            )
                        })
                    }
                </Container>
            </div>
        </>
    )
}
Example #24
Source File: useIsomorphicLayoutEffect.js    From Path-Finding-Visualizer with MIT License 5 votes vote down vote up
useIsomorphicLayoutEffect = typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined' ? useLayoutEffect : useEffect
Example #25
Source File: Elements.js    From Elemento with MIT License 5 votes vote down vote up
Element = ({uncheckBox}) => {
  const classes = useStyles();

  const elementContext = useContext(ElementContext);
  const { getElements, elements,filtered } = elementContext;

  useEffect(() => {
    if(elements === null){
      getElements();
    };
    clearSelected();

  }, []);

  if (elements === null) {
    return <div className="loading"><img src={Loader}></img> </div>;
  }
  return (
    <Fragment>
    <Container maxWidth='lg'>

      <div className={classes.root}>
        {filtered === null
          ? elements.map((element) => (
            <ElementItem
              JSCode={element.JSCode}
              HTMLCode={element.HTMLCode}
              CSSCode={element.CSSCode}
              name={element.name}
              img={element.screenshot.data}
              key={element._id}
              id={element._id}
              clearCheckBox={uncheckBox}
            />
          )):  filtered.map((element) => (
              <ElementItem
              JSCode={element.JSCode}
              HTMLCode={element.HTMLCode}
              CSSCode={element.CSSCode}
                name={element.name}
                img={element.screenshot.data}
                key={element._id}
                id={element._id}
              />
            ))}
      </div>
    </Container>
    </Fragment>
  );
}
Example #26
Source File: navbar.jsx    From website with BSD Zero Clause License 5 votes vote down vote up
Navbar = ({ usarTransparencia, currentPage }) => {
  const [scrolled, setScrolled] = React.useState(false);
  const [usuario] = useState(obtUsuarioStorage());

  useEffect(() => {
    window.addEventListener("scroll", handleScroll)
    return () => window.removeEventListener("scroll", handleScroll)
  }, [scrolled])
  let x = ["fixed-top"]
  if (!usarTransparencia || scrolled) {
    x.push("scrolled")
  }

  const handleScroll = () => {
    const offset = window.scrollY
    if (offset > 20) {
      setScrolled(true)
    } else {
      setScrolled(false)
    }
  }

  const salir = (e) => {
    e.preventDefault();
    cerrarSesion()
      .then(res => {
        if (res) {
          localStorage.removeItem('usuario');
        }
      })
  }

  return (
    <div className={x.join(" ")}>
      <div className="contenedor contenedor-navbar">
        <nav className="navbar navbar-expand-md navbar-dark">
          <Link className="navbar-brand logo" to="/">
            <img src={Logo} alt="Logo" title="Logo" />
          </Link>
          <button
            className="navbar-toggler"
            type="button"
            data-toggle="collapse"
            data-target="#collapsibleNavbar"
          >
            <span className="navbar-toggler-icon"></span>
          </button>

          <div className="collapse navbar-collapse" id="collapsibleNavbar">
            <ul className="navbar-nav ml-auto mr-5">
              {
                usuario && currentPage && currentPage == '/admin'
                  ?
                  <li className="nav-item">
                    <a onClick={salir}>Salir</a>
                  </li>
                  :
                  <>
                    <li className="nav-item">
                      <Link to="/">Inicio</Link>
                    </li>
                    <li className="nav-item">
                      <Link to="/courses">Cursos</Link>
                    </li>
                    <li className="nav-item">
                      <Link to="/teachers">Docentes</Link>
                    </li>
                  </>
              }
            </ul>
          </div>
        </nav>
      </div>
    </div>
  )
}