react#useContext JavaScript Examples

The following examples show how to use react#useContext. 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: chat.js    From rsc-www with GNU Affero General Public License v3.0 6 votes vote down vote up
export default function IRC() {
    const { user } = useContext(SessionContext);
    console.log(user);
    const nick = user && user.id ? formatUsername(user.username) : '';
    const ircURL =
        `https://kiwiirc.com/nextclient/irc.rizon.net/?nick=${nick}#2003scape`;

    return (
        <div>
            <Header pageName={`${PAGE_TITLE} - Community`} />
            <Container>
                <PageName pageName={PAGE_TITLE}>
                    <Link href="/community">
                        <a className="rsc-link rsc-small-block rsc-small-spaced">
                            Community
                        </a>
                    </Link>
                </PageName>
                <div className="rsc-row">
                    <div className="rsc-col rsc-col-100">
                        <iframe
                            className="rsc-box"
                            style={{ width: '100%', height: '532px' }}
                            src={ircURL}
                        />
                    </div>
                </div>
            </Container>
        </div>
    );
}
Example #2
Source File: SignUpCard.js    From bunk-manager-mern with MIT License 6 votes vote down vote up
SignUpCard = (props) => {
  const classes = useStyles(props);
  const {googleLogin} = useContext(AuthContext);
  return (
    <React.Fragment>
      <Typography color="primary" className={classes.signUpHeader} variant="h5">
        Sign Up
      </Typography>
      <p>using</p>
      <div className={classes.oAuthDiv}>
        {/* <Button>
          <FacebookIcon className={classes.fb}/>
        </Button> */}
        <Button onClick={()=>googleLogin()}>
          <img src={google} alt="Google" width="30" height="30" />
        </Button>
      </div>
      <Typography color="primary" className={classes.p} variant="h6">
        <Divider />
        OR
      </Typography>
      <Button className={classes.button} component={Link} to="/user/signup">

        Register

      </Button>
    </React.Fragment>
  );
}
Example #3
Source File: useReduxContext.js    From Path-Finding-Visualizer with MIT License 6 votes vote down vote up
/**
 * A hook to access the value of the `ReactReduxContext`. This is a low-level
 * hook that you should usually not need to call directly.
 *
 * @returns {any} the value of the `ReactReduxContext`
 *
 * @example
 *
 * import React from 'react'
 * import { useReduxContext } from 'react-redux'
 *
 * export const CounterComponent = ({ value }) => {
 *   const { store } = useReduxContext()
 *   return <div>{store.getState()}</div>
 * }
 */

export function useReduxContext() {
  var contextValue = useContext(ReactReduxContext);

  if (process.env.NODE_ENV !== 'production' && !contextValue) {
    throw new Error('could not find react-redux context value; please ensure the component is wrapped in a <Provider>');
  }

  return contextValue;
}
Example #4
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 #5
Source File: LinkContainer.js    From apps-base-schema with MIT License 6 votes vote down vote up
/**
 * Container group for the link path elements. Handles node mouseover/mouseout (event delegation
 * done in the HighlightWrapper).
 *
 * Note: `props.linkPathsByLinkId` is only used for the initial render, and whenever the base
 * schema changes. Aside from that, it is never changed via React, so the value here is actually
 * stale. This is because we updated the path `d` values during mousemove, and never push this
 * state from the DOM back into React world upon finishing dragging. This could be done by
 * extracting the `d` attribute from all links on drag finish, but it works fine as is.
 *
 * @param {Object} props.linksById all link objects, by id
 * @param {Object} props.linkPathsByLinkId all link paths, by id
 * @param {Object} props.enabledLinksByType whether each link type is enabled, by link type
 */
export default function LinkContainer({linksById, linkPathsByLinkId, enabledLinksByType}) {
    const {onNodeOrLinkMouseOver, onNodeOrLinkMouseOut} = useContext(HighlightContext);

    return (
        <g
            id="link-container"
            onMouseMove={onNodeOrLinkMouseOver}
            onMouseOut={onNodeOrLinkMouseOut}
        >
            {Object.values(linksById).map(link => {
                const isEnabled = enabledLinksByType[link.type];

                return (
                    <path
                        display={isEnabled ? undefined : 'none'}
                        key={link.id}
                        id={link.id}
                        className={`Link ${link.type}`}
                        d={linkPathsByLinkId[link.id]}
                    />
                );
            })}
        </g>
    );
}
Example #6
Source File: CartButton.js    From Next.js-e-commerce-online-store with MIT License 6 votes vote down vote up
export default function CartButton() {
  const { cartBadgeToggle } = useContext(CartContext)

  const [ itemsAmountInCart, setItemsAmountInCart ] = useState(0)

  const assignProductAmountInCart = () => {
    const cartList = JSON.parse(localStorage.cartList)
    const cartListLength = cartList.length

    setItemsAmountInCart(cartListLength)
  }

  useEffect(() => {
    if (localStorage.getItem('cartList') !== null) {
      assignProductAmountInCart()
    } else {
      setItemsAmountInCart(0)
    }   
  },[cartBadgeToggle])

  return (
    <Link href="/cart">
      <a aria-label="Shopping cart link">
        <FontAwesomeIcon icon={faShoppingCart} size="lg" />
        {
          itemsAmountInCart > 0
          ? <DivIconAmountInCart>
              {itemsAmountInCart}
            </DivIconAmountInCart>
          : null
        }
      </a>
    </Link>
  )
}
Example #7
Source File: Button.js    From ResumeOnTheWeb-Gatsby with MIT License 6 votes vote down vote up
Button = ({ type, className, icon, title, onClick, disabled }) => {
  const { dark } = useContext(ThemeContext);
  const Icon = icon;

  return (
    <button
      type={type}
      onClick={onClick}
      disabled={disabled}
      className={`${styles.container} ${className} ${!dark && styles.light}`}
    >
      <div>
        <Icon />
        <h6>{title}</h6>
      </div>
      <div />
    </button>
  );
}
Example #8
Source File: ThemePicker.js    From viade_en1b with MIT License 6 votes vote down vote up
ThemePicker = () => {
  const { theme, changeTheme } = useContext(ThemeContext);
  const buttons = Object.keys(themes).map((key, index) => {
    return (
      <Dropdown.Item key={index} onClick={() => changeTheme(themes[key])}>
        {themes[key].name}
      </Dropdown.Item>
    );
  });

  return (
    <Dropdown className={style.picker}>
      <Dropdown.Toggle variant="success" id="dropdown-basic">
        <FormattedMessage id="Themes" />: {theme.name}
      </Dropdown.Toggle>

      <Dropdown.Menu>{buttons}</Dropdown.Menu>
    </Dropdown>
  );
}
Example #9
Source File: ClassList.js    From front-end with MIT License 6 votes vote down vote up
ClassList = () => {
  const { session, setSession } = useContext(InitialContext);
  console.log(session);
  useEffect(() => {
    axiosWithAuth()
      .get("/classes")
      .then((res) => {
        console.log(res);
        setSession(res.data);
      })
      .catch((err) => console.log(err.message));
  }, []);

  return (
    <>
      <div>
          <ClassSearch session={session} />
        
      </div>
    </>
  );
}
Example #10
Source File: App.js    From connect-4-online-multiplayer with MIT License 6 votes vote down vote up
function App() {
  const user = useContext(UserContext);

  if (!user.id) {
    return <Login />;
  }

  return (
    <SocketProvider id={user.id}>
      <NavBar />
      <Switch>
        <Route path="/" exact>
          <Rooms />
        </Route>
        <Route path="/game">
          <Box py={4}>
            <Game />
          </Box>
        </Route>
      </Switch>
    </SocketProvider>
  );
}
Example #11
Source File: Landing.js    From covid-tracker-material-ui-react with MIT License 6 votes vote down vote up
function Landing() {
  const classes = useStyles();
  const data = useContext(DataContext);

  return (
    <div className={classes.root}>
      {data.hasLoaded ? (
        <Grid container className={classes.container}>
          <Grid item xs={12} sm={6} className={classes.left}>
            <LeftLanding />
          </Grid>
          <Grid item xs={12} sm={6} className={classes.right}>
            <RightLanding />
          </Grid>
        </Grid>
      ) : (
        <div className={classes.spinner}>
          <CircularProgress color="secondary" />
        </div>
      )}
    </div>
  );
}
Example #12
Source File: InventoryModal.js    From CyberStateRP with MIT License 6 votes vote down vote up
InventoryModal = props => {
    const { inv } = useContext(InventoryContext)

    return (
        <div
            className="invModal"
            style={
                {
                    display: inv.modal.active ? 'block' : 'none',
                    top: inv.modal.top,
                    left: inv.modal.left,
                }
            }
        >
            {inv.modal.desc}
        </div>
    )
}
Example #13
Source File: MemberCard.js    From video-journal-for-teams-fe with MIT License 6 votes vote down vote up
function MemberCard(props) {
	const userRole = useContext(UserContext);

	const { data } = props;
	const isSelf = data.user_id === props.userId;

	return (
		<Card className="member-card" bordered={false} hoverable>
			<div className="image-container">
				{!data.avatar ? (
					<Avatar size={64} icon="user" />
				) : (
					<img alt="user avatar" src={`${process.env.REACT_APP_S3_STORAGE_PATH}${data.avatar}`} />
				)}
			</div>
			<p className="small">{data.user_full_name}</p>

			{typeof userRole == "undefined" ? null : userRole.userRole === 1 ? null : (
				<EditMemberCard member={data} isSelf={isSelf} />
			)}
		</Card>
	);
}
Example #14
Source File: VerifiedUser.js    From workout-tracker-fe-pt with MIT License 6 votes vote down vote up
VerifiedUser = () => {
  const { userInfo } = useContext(ProfileContext);

  const CheckVerification = () => {
    if (userInfo.verified === true) {
      return <VerifiedBadge2 src={Verified} alt="Verified Badge Enabled" title="You are verified."/>;
    } else {
      return <VerifiedBadge src={Verified} alt="Verified Badge Disabled" title="Not verified."/>;
    }
  };
  return (
    <>
      <p> {CheckVerification()}</p>
    </>
  );
}
Example #15
Source File: Alert.js    From usfm-grammar-online with MIT License 6 votes vote down vote up
export default function Alert() {
  const { message, severity, setMessage } = useContext(GrammarContext);

  const handleClose = (event, reason) => {
    if (reason === "clickaway") {
      return;
    }
    setMessage("");
  };
  return (
    <Snackbar
      anchorOrigin={{ vertical: "top", horizontal: "center" }}
      open={Boolean(message)}
      autoHideDuration={6000}
      onClose={handleClose}
    >
      <MuiAlert
        elevation={6}
        variant="filled"
        onClose={handleClose}
        severity={severity}
      >
        {message}
      </MuiAlert>
    </Snackbar>
  );
}
Example #16
Source File: infobox.js    From website with Apache License 2.0 6 votes vote down vote up
Infobox = ({ children }) => {
  const mapContext = useContext(MapContext)

  return (
    <div
      className={infoboxStyle.infobox}
      style={{
        left: Math.max(10, mapContext.infoboxPosition.x - 175),
        top: mapContext.infoboxPosition.y + 15,
      }}
    >
      {children}
    </div>
  )
}
Example #17
Source File: Buttons.js    From Front-end-learning-to-organize-notes with MIT License 6 votes vote down vote up
function Buttons() {
    const { dispatch } = useContext(ColorContext)
    return (
        <div>
            <button onClick={() => { dispatch({ type: UPDATE_COLOR, color: "red" }) }}>红色</button>
            <button onClick={() => { dispatch({ type: UPDATE_COLOR, color: "yellow" }) }}>黄色</button>
        </div>
    )
}
Example #18
Source File: ArrowBack.js    From Alfredo-Mobile with MIT License 6 votes vote down vote up
ArrowBack = (props) => {
  const {...restProps} = props
  const navigation = useContext(NavigationContext)

  return (
    <TouchableOpacity activeOpacity={0.9} style={styles.container} onPress={() => navigation.goBack()}>
      <Icon name="chevron-left" size={35} color={apply('gray-900')} />
    </TouchableOpacity>
  )
}
Example #19
Source File: EditLink.js    From storybook-documentation-primitives with MIT License 6 votes vote down vote up
EditLink = ({ path, text, icon }) => {
  const {
    parameters: { repository },
  } = useContext(DocsContext);

  if (!repository) {
    return (
      <P>Can&rsquo;t render EditLink: `repository` parameter is missing.</P>
    );
  }

  if (!path) {
    return <P>Can&rsquo;t render EditLink: `path` prop is missing.</P>;
  }

  const { baseUrl, branch = 'master' } = repository;
  const href = `${baseUrl}/edit/${branch}/${path}`;

  return (
    <P>
      <Link href={href} rel="noopener noreferrer" target="_blank">
        {icon && <Icon icon="github" aria-hidden />}
        <Text>{text}</Text>
      </Link>
    </P>
  );
}
Example #20
Source File: App.js    From roomie-frontend with MIT License 6 votes vote down vote up
App = () => {
  const { userId } = useContext(Context);
  const { isHost } = useContext(Context);
  const isLogged = userId && (isHost !== null);
  const isLoggedHost = isLogged && isHost;

  return (
    <BrowserRouter>
      <GlobalStyle />
      <Switch>
        <Route exact path='/' component={isLogged ? Home : Signin} />
        <Route exact path='/signin' component={isLogged ? Home : Signin} />
        <Route exact path='/signup' component={isLogged ? Home : Signup} />
        <Route exact path='/create/place' component={isLoggedHost ? CreatePlace : Home} />
        <Route exact path='/create/profile' component={isLogged ? Home : CreateProfile} />
        <Route exact path='/places/:placeId' component={isLogged ? ViewRoom : Signin} />
        <Route exact path='/favorites' component={isLogged ? Favorites : Signin} />
        <Route exact path='/profile/:profileId' component={ViewProfile} />
        <Route component={NotFound} />
      </Switch>
    </BrowserRouter>
  );
}
Example #21
Source File: ProfilePage.js    From React-Messenger-App with MIT License 6 votes vote down vote up
ProfilePage = () => {
  const user = useContext(UserContext);
  const {photoURL, displayName, email} = user;
  return (
    <div className = "mx-auto w-11/12 md:w-2/4 py-8 px-4 md:px-8">
      <div className="flex border flex-col items-center md:flex-row md:items-start border-blue-400 px-3 py-4">
        <div
          style={{
            background: `url(${photoURL || 'https://res.cloudinary.com/dqcsk8rsc/image/upload/v1577268053/avatar-1-bitmoji_upgwhc.png'})  no-repeat center center`,
            backgroundSize: "cover",
            height: "200px",
            width: "200px"
          }}
          className="border border-blue-300"
        ></div>
        <div className = "md:pl-4">
        <h2 className = "text-2xl font-semibold">{displayName}</h2>
        <h3 className = "italic">{email}</h3>
        </div>
      </div>
      <button className = "w-full py-3 bg-red-600 mt-4 text-white" onClick = {() => {auth.signOut()}}>Sign out</button>
    </div>
  ) 
}
Example #22
Source File: CreateRoleCommand.js    From Website with MIT License 6 votes vote down vote up
CreateRoleCommand = ({ setCreatingCommand, guild: userConnectedGuildInfo }) => {
	const { roleToGive, setRoleToGive } = useContext(CommandContext);
	return (
		<>
			<h4 className="plugin-section-title">Role To give</h4>
			<div className="plugin-section">
				<StyledSelect
					closeMenuOnSelect
					onChange={e => {
						setRoleToGive(e);
					}}
					placeholder="Select Command Role"
					value={roleToGive}
					options={userConnectedGuildInfo?.roles
						?.filter(role => role.name !== "@everyone")
						?.filter(role => !role.managed)
						?.sort((a, b) => b.rawPosition - a.rawPosition)
						?.map(role => ({
							value: `${role.name}=${JSON.stringify(role)}`,
							label: <RoleItem {...role}>{role.name}</RoleItem>,
						}))}
				/>
			</div>
		</>
	);
}
Example #23
Source File: use-deck.js    From MDXP with MIT License 5 votes vote down vote up
useDeck = () => useContext(DeckContext)[0]
Example #24
Source File: Application.js    From about-1hive with GNU General Public License v3.0 5 votes vote down vote up
function useApplicationContext() {
  return useContext(ApplicationContext)
}
Example #25
Source File: AppState.js    From tulip-frontend with GNU Affero General Public License v3.0 5 votes vote down vote up
function useAppState() {
  return useContext(AppStateContext)
}
Example #26
Source File: Allowances.js    From uniswap-v1-frontend with GNU General Public License v3.0 5 votes vote down vote up
function useAllowancesContext() {
  return useContext(AllowancesContext)
}
Example #27
Source File: [...article].js    From rsc-www with GNU Affero General Public License v3.0 5 votes vote down vote up
export default function NewsArticle(props) {
    const pageTitle = `${props.article.title} - ${PAGE_TITLE}`;
    const articleHTML = { __html: markdown.render(props.article.body) };

    const { user } = useContext(SessionContext);

    let editArticle;

    if (user && user.rank === 3) {
        const confirmDelete = (event) => {
            if (
                !window.confirm(
                    `Are you sure you wish to delete "${props.article.title}"?`
                )
            ) {
                event.preventDefault();
                return false;
            }
        };

        editArticle = (
            <>
                <p className="rsc-centre-text" style={{ fontSize: '14px' }}>
                    <Link href={`/news/write?id=${props.article.id}`}>
                        <a className="rsc-link" style={{ display: 'block' }}>
                            ➕ Edit news article
                        </a>
                    </Link>
                    <br />
                    <a
                        href={`/api/news?id=${props.article.id}&delete=true`}
                        className="rsc-link"
                        style={{ display: 'block' }}
                        onClick={confirmDelete}
                    >
                        ❌ Delete news article
                    </a>
                </p>
                <hr />
            </>
        );
    }

    return (
        <div>
            <Header pageName={pageTitle} />
            <Container>
                <PageName pageName={PAGE_TITLE}>
                    <Link href="/news">
                        <a className="rsc-link rsc-small-block rsc-small-spaced">
                            All News
                        </a>
                    </Link>
                </PageName>
                <div className="rsc-row">
                    <div className="rsc-col rsc-col-100">
                        <main className="rsc-box rsc-article-box">
                            {editArticle}
                            <h1>
                                <time>
                                    {formateDate(
                                        new Date(props.article.date * 1000)
                                    )}
                                </time>
                                &nbsp;-&nbsp;
                                {props.article.title}
                            </h1>
                            <div dangerouslySetInnerHTML={articleHTML} />
                            <div style={{ clear: 'both' }} />
                        </main>
                    </div>
                </div>
            </Container>
        </div>
    );
}
Example #28
Source File: LoginPage.js    From bunk-manager-mern with MIT License 5 votes vote down vote up
LoginPage = (props) => {
  const classes = useStyles(props);
  const { darkMode } = useContext(DarkThemeContext);
  const containerVariants = {
    hidden: {
      opacity: 0,
    },
    visible: {
      opacity: 1,

      transition: {
        delay: 0.5,
        duration: 0.5,
      },
    },
    exit: {
      x: "-100vw",
      transition: { ease: "easeInOut" },
    },
  };

  return (
    <motion.div
      variants={containerVariants}
      initial="hidden"
      animate="visible"
      exit="exit"
      className={classes.container}
    >
      <Grid container className={classes.containerGrid}>
        <Grid item xs={12} sm={12} md={8}>
          {darkMode ? (
            <img src={svgImgDark} alt="svgimage" className={classes.svgImg} />
          ) : (
            <img src={svgImg} alt="svgimage" className={classes.svgImg} />
          )}
        </Grid>
        <Grid className={classes.gridItem} item xs={12} sm={12} md={4}>
          <AuthenticationCard />
        </Grid>
      </Grid>
    </motion.div>
  );
}
Example #29
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>
  );
}