react#Fragment JavaScript Examples

The following examples show how to use react#Fragment. 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: AdvancedProfile.js    From acy-dex-interface with MIT License 7 votes vote down vote up
action = (
  <Fragment>
    <ButtonGroup>
      <Button>操作</Button>
      <Button>操作</Button>
      <Dropdown overlay={menu} placement="bottomRight">
        <Button>
          <Icon type="ellipsis" />
        </Button>
      </Dropdown>
    </ButtonGroup>
    <Button type="primary">主操作</Button>
  </Fragment>
)
Example #2
Source File: Routes.js    From tisn.app with GNU Affero General Public License v3.0 6 votes vote down vote up
PublicRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={(props) =>
      !isLoggedIn() ? (
        <Fragment>
          <WelcomeNavigationBar />
          <Component {...props} />
        </Fragment>
      ) : (
        <Redirect to={{ pathname: '/' }} />
      )
    }
  />
)
Example #3
Source File: App.js    From TrelloClone with MIT License 6 votes vote down vote up
App = () => {
  useEffect(() => {
    store.dispatch(loadUser());
  }, []);

  return (
    <Provider store={store}>
      <Router>
        <Fragment>
          <Alert />
          <Switch>
            <Route exact path='/' component={Landing} />
            <Route exact path='/register' component={Register} />
            <Route exact path='/login' component={Login} />
            <Route exact path='/dashboard' component={Dashboard} />
            <Route exact path='/board/:id' component={Board} />
          </Switch>
        </Fragment>
      </Router>
    </Provider>
  );
}
Example #4
Source File: App.js    From viade_es2a with BSD 2-Clause "Simplified" License 6 votes vote down vote up
App = () => (
  <Suspense fallback={<Loader />}>
    <Fragment>
      <Routes />
      <Toaster
        {...{
          autoClose: 5000,
          position: toast.POSITION.TOP_CENTER,
          newestOnTop: true,
          closeOnClick: true,
          pauseOnVisibilityChange: true,
          draggable: true,
          className: 'solid-toaster-container',
          toastClassName: 'solid-toaster',
          bodyClassName: 'solid-toaster-body',
          transition: Slide
        }}
      />
    </Fragment>
  </Suspense>
)
Example #5
Source File: CloudinaryWidget.js    From Merch-Dropper-fe with MIT License 6 votes vote down vote up
ImageUpload = ({ design, setDesign, designAdded, setDesignAdded }) => {
  const classes = useStyles();
  let widget = window.cloudinary.createUploadWidget(
    {
      cloudName: "dze74ofbf",
      uploadPreset: "logoFromWidget",
      sources: ["local", "url"],
      showAdvancedOptions: false,
      cropping: false,
      multiple: false,
      defaultSource: "local"
    },
    (error, result) => {
      if (result.event === "success") {
        const data = result.info;

        setDesign({
          ...design,
          design_name: data.original_filename,
          design_url: data.url,
          thumbnail_url: data.thumbnail_url
        });
        setDesignAdded(designAdded + 1);
      }
    }
  );

  const showWidget = function() {
    widget.open();
  };

  return (
    <Fragment>
      <button className={classes.button} onClick={showWidget}>
        Upload New Design
      </button>
    </Fragment>
  );
}
Example #6
Source File: Activity.js    From quake-fe with MIT License 6 votes vote down vote up
Activity = () => {
  return (
    <Fragment>
      <MediaQuery minWidth={800}>
        <SearchBar />
      </MediaQuery>
      <div className="main-container no-scroll activity-page">
        <MediaQuery maxWidth={799}>
          <SearchBar />
        </MediaQuery>
        <Filters />
        <ResultsContainer />
        <MapContainer />
      </div>
    </Fragment>
    
  );
}
Example #7
Source File: format.js    From website with Apache License 2.0 6 votes vote down vote up
FormatItemList = ({ items, keys, useAmpersand = true }) => {
  const { length } = items
  return (
    <>
      {items.map((item, index) => {
        const listSpacer = getListSpacer(index, length, useAmpersand)
        return (
          <Fragment key={keys[index]}>
            {item}
            {listSpacer === '' ? undefined : listSpacer}
          </Fragment>
        )
      })}
    </>
  )
}
Example #8
Source File: App.js    From Stack-PERN-Boilerplate with MIT License 6 votes vote down vote up
function App() {
  const [counter, setCounter] = useState(42);
  const incrementCounter = (incrementValue) => setCounter(counter+incrementValue);

  return (
    <Fragment>
        <div className="container">
            <InputTodo />
            <ListTodos />
            <LittleButton onClickFunction={incrementCounter}
                          increment={1} />
            <LittleButton onClickFunction={incrementCounter}
                          increment={5} />
            <LittleButton onClickFunction={incrementCounter}
                          increment={10} />
            <LittleButton onClickFunction={incrementCounter}
                          increment={100} />
            <DisplayIncrement message={counter} />
        </div>
    </Fragment>
  );
}
Example #9
Source File: App.js    From college-management-react with GNU General Public License v3.0 6 votes vote down vote up
render() {
    return (
      <Fragment>
        {this.state.tokenChecked && (
          <MuiPickersUtilsProvider utils={DateFnsUtils}>
            <Router>
              <Navbar />
              <Grid container spacing={0}>
                <Grid item md={3} />
                <Grid item xs={12} md={6}>
                  <Routes />
                </Grid>
              </Grid>
              <Footer />
            </Router>
          </MuiPickersUtilsProvider>
        )}
      </Fragment>
    );
  }
Example #10
Source File: _document.js    From Uno_Game with MIT License 6 votes vote down vote up
render() {
    return (
      <Html lang={documentLang(this.props)}>
        <Head>
          {/* Global Site Tag (gtag.js) - Google Analytics */}
          {process.env.GA_TRACKING_ID && (
            <Fragment>
              <script
                async
                src={`https://www.googletagmanager.com/gtag/js?id=${process.env.GA_TRACKING_ID}`}
              />
              <script
                dangerouslySetInnerHTML={{
                  __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${process.env.GA_TRACKING_ID}', {
              page_path: window.location.pathname,
            });
          `,
                }}
              />
            </Fragment>
          )}
          <link rel="preconnect" href="https://www.google-analytics.com" />
          <link rel="preconnect" href="https://firestore.googleapis.com" />
        </Head>
        <body className="font-sans leading-normal">
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
Example #11
Source File: Previews.js    From halo-lab with MIT License 6 votes vote down vote up
Previews = (props) => {
  const items = useWordpressPosts();

  return (
    <Fragment>
      <Switcher items={items} page={props.page}/>
    </Fragment>
  );
}
Example #12
Source File: Dashboard.js    From CPTracker with MIT License 6 votes vote down vote up
Dashboard = (props) => {
  const { sites } = props;
  return (
    <Fragment>
      <div className="row" style={{ height: "15px" }}>
        {" "}
      </div>
      {sites.length && sites.map((el) => <IntroCard info={el} key={el.id} />)}
    </Fragment>
  );
}
Example #13
Source File: App.js    From mongodb-graphql-demo with Apache License 2.0 6 votes vote down vote up
function App() {
	const {
		isLoggedIn,
		actions: { handleAnonymousLogin },
	} = useStitchAuth();

	const [isLoading, setLoadingState] = useState(false);

	if (!isLoggedIn) {
		setLoadingState(true);
		handleAnonymousLogin();
	}

	return <Fragment>{isLoading ? <Loading /> : <InstaPostApp />}</Fragment>;
}
Example #14
Source File: layout.js    From guitar-book with MIT License 6 votes vote down vote up
export default function Layout(props) {
  return (
    <StaticQuery
      query={graphql`
        {
          site {
            siteMetadata {
              title
              description
            }
          }
        }
      `}
      render={data => {
        const {title, description} = data.site.siteMetadata;
        return (
          <Fragment>
            <Helmet defaultTitle={title} titleTemplate={`%s - ${title}`}>
              <meta name="description" content={description} />
            </Helmet>
            {props.children}
          </Fragment>
        );
      }}
    />
  );
}
Example #15
Source File: App.js    From ReactJS-Projects with MIT License 6 votes vote down vote up
AgentBond = () => {
  return (
    <MyContext.Consumer>
      {
        context => (
          <Fragment>
            <h3> Agent Info </h3>
            <p>Mission Name: {context.data.missonName}</p>
            <p>Mission Status: {context.data.accepted}</p>
            <button onClick={context.isMissionAccepted}>ACCEPT</button>
          </Fragment>
        )
      }
    </MyContext.Consumer>
  )
}
Example #16
Source File: index.jsx    From react-big-screen with MIT License 6 votes vote down vote up
render() {
    const { title } = this.state;
    return (
      <Fragment>
        <TopBox>
          <div className='top_box'>
            <Decoration10 className='top_decoration10' />
            <div className='title-box'>
              <Decoration8
                className='top_decoration8'
                color={['#568aea', '#000000']}
              />
              <div className='title'>
                <span className='title-text'>{title}</span>
                <Decoration6
                  className='title-bototm top_decoration6'
                  reverse={true}
                  color={['#50e3c2', '#67a1e5']}
                />
              </div>

              <Decoration8
                reverse={true}
                className='top_decoration8'
                color={['#568aea', '#000000']}
              />
            </div>
            <Decoration10 className='top_decoration10 top_decoration10_reverse' />
            <TimeBox>
              <h3>{this.state.timeStr}</h3>
            </TimeBox>
          </div>
        </TopBox>
      </Fragment>
    );
  }
Example #17
Source File: BaseButton.component.jsx    From Stackoverflow-Clone-Frontend with MIT License 6 votes vote down vote up
BaseButton = ({text, selected, onClick}) => {
  return (
    <Fragment>
      <button
        className={`s-btn s-btn__filled ${
          selected === text ? 'is-selected' : ''
        }`}
        style={{margin: '0'}}
        onClick={onClick}
      >
        {text}
      </button>
    </Fragment>
  );
}
Example #18
Source File: ErrorBoundary.js    From lens-extension-cc with MIT License 6 votes vote down vote up
render() {
    const { testId } = this.props;
    const { error } = this.state;

    if (error !== undefined) {
      return (
        <div data-testid={testId}>
          {error instanceof Error && (
            <Fragment>
              <div data-testid={`${testId}-message`}>{error.message}</div>
              <div data-testid={`${testId}-stack`}>{error.stack}</div>
            </Fragment>
          )}
          {!(error instanceof Error) && (
            <div data-testid={`${testId}-value`}>{error + ''}</div>
          )}
        </div>
      );
    }

    return this.props.children;
  }
Example #19
Source File: BudgetSummary.js    From Simplify-Testing-with-React-Testing-Library with MIT License 6 votes vote down vote up
BudgetSummary = ({ classes, income, spending, leftover }) => {
  const getLeftOverClass = () => {
    if (leftover > 0) {
      return classes.profit;
    } else if (leftover === 0) {
      return classes.neutral;
    }
    return classes.debt;
  };

  return (
    <Fragment>
      <Card className={classes.card} raised={true}>
        <CardContent>
          <Typography variant='h6'>You've budgeted...</Typography>
          <Typography variant='subtitle1'>Income: ${income}</Typography>
          <Typography variant='subtitle1'>
            Spending: <span className={classes.debt}>${spending}</span>
          </Typography>
          <hr />
          <Typography className={classes.leftoverText}>
            Left over: <span className={getLeftOverClass()}>${leftover}</span>
          </Typography>
        </CardContent>
      </Card>
    </Fragment>
  );
}
Example #20
Source File: PublicationEditor.js    From paras-landing with GNU General Public License v3.0 6 votes vote down vote up
CardPublication = ({ localToken, deleteCard }) => {
	const { localeLn } = useIntl()
	return (
		<Fragment>
			<div className="w-full m-auto">
				<Card
					imgUrl={parseImgUrl(localToken.metadata.media, null, {
						width: `600`,
						useOriginal: process.env.APP_ENV === 'production' ? false : true,
						isMediaCdn: localToken.isMediaCdn,
					})}
					imgBlur={localToken.metadata.blurhash}
					token={{
						title: localToken.metadata.title,
						collection: localToken.metadata.collection || localToken.contract_id,
						copies: localToken.metadata.copies,
						creatorId: localToken.metadata.creator_id || localToken.contract_id,
						is_creator: localToken.is_creator,
					}}
				/>
			</div>
			<div className="text-gray-100 pt-4">
				<div className=" overflow-hidden">
					<p
						title={localToken?.metadata?.title}
						className="text-2xl font-bold border-b-2 border-transparent truncate"
					>
						{localToken?.metadata?.title}
					</p>
				</div>
				<p className="opacity-75 truncate">{localToken?.metadata?.collection}</p>
			</div>
			<div className="text-red-600 text-sm cursor-pointer" onClick={deleteCard}>
				{localeLn('Delete')}
			</div>
		</Fragment>
	)
}
Example #21
Source File: Skills.jsx    From developer-portfolio with Apache License 2.0 5 votes vote down vote up
Skills = () => {
	return (
		<Container className="text-center my-5 section section-lg">
			<h1 className="h1">{skillsSection.title}</h1>
			<p className="lead">{skillsSection.subTitle}</p>
			{skillsSection.data.map((section, index) => {
				return (
					<Row className="my-5" key={index}>
						<Col lg="6" className="order-2 order-lg-1">
							<Fade left duration={2000}>
								<DisplayLottie
									animationPath={section.lottieAnimationFile}
								/>
							</Fade>
						</Col>
						<Col lg="6" className="order-1 order-lg-2">
							<Fade right duration={2000}>
								<h3 className="h3 mb-2">{section.title}</h3>
								<div className="d-flex justify-content-center flex-wrap mb-2">
									{section.softwareSkills.map((skill, i) => {
										return (
											<Fragment key={i}>
												<div
													className="icon icon-lg icon-shape shadow-sm rounded-circle m-1"
													id={skill.skillName.replace(/\s/g, '')}
												>
													<Icon
														icon={
															skill.fontAwesomeClassname
														}
														data-inline="false"
													></Icon>
												</div>
												<UncontrolledTooltip
													delay={0}
													placement="bottom"
													target={skill.skillName.replace(/\s/g, '')}
												>
													{skill.skillName}
												</UncontrolledTooltip>
											</Fragment>
										);
									})}
								</div>
								<div>
									{section.skills.map((skill, i) => {
										return <p key={i}>{skill}</p>;
									})}
								</div>
							</Fade>
						</Col>
					</Row>
				);
			})}
		</Container>
	);
}
Example #22
Source File: index.js    From acy-dex-interface with MIT License 5 votes vote down vote up
getNotificationBox() {
    const { visible } = this.state;
    const { children, loading, locale } = this.props;
    if (!children) {
      return null;
    }
    const panes = React.Children.map(children, child => {
      const {
        list,
        title,
        name,
        count,
        emptyText,
        emptyImage,
        showClear,
        loadedAll,
        scrollToLoad,
        skeletonCount,
        skeletonProps,
        loading: tabLoading,
      } = child.props;
      const len = list && list.length ? list.length : 0;
      const msgCount = count || count === 0 ? count : len;
      const tabTitle = msgCount > 0 ? `${title} (${msgCount})` : title;
      return (
        <TabPane tab={tabTitle} key={name}>
          <List
            data={list}
            emptyImage={emptyImage}
            emptyText={emptyText}
            loadedAll={loadedAll}
            loading={tabLoading}
            locale={locale}
            onClear={() => this.onClear(name)}
            onClick={item => this.onItemClick(item, child.props)}
            onLoadMore={event => this.onLoadMore(child.props, event)}
            scrollToLoad={scrollToLoad}
            showClear={showClear}
            skeletonCount={skeletonCount}
            skeletonProps={skeletonProps}
            title={title}
            visible={visible}
          />
        </TabPane>
      );
    });
    return (
      <Fragment>
        <Spin spinning={loading} delay={0}>
          <Tabs className={styles.tabs} onChange={this.onTabChange}>
            {panes}
          </Tabs>
        </Spin>
      </Fragment>
    );
  }
Example #23
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 #24
Source File: WebPlayer.jsx    From Oud with MIT License 5 votes vote down vote up
render() {
    return (
      <Fragment>
        <Queue
          ref={this.queueElement}
          tracks={this.state.queue}
          trackId={this.state.trackId}
          trackIdx={this.state.trackIdx}
          deviceId={this.state.deviceId}
          playing={this.state.playing}
          changePlayingState={this.changePlayingState}
          onChangeQueueOrder={this.onChangeQueueOrder}
          player={this.playerElement}
          removeTrack={this.removeTrack}
          likeSong={this.likeSong}
          unlikeSong={this.unlikeSong}
          data-testid="queue-container"
        />
        <Player
          ref={this.playerElement}
          trackId={this.state.trackId}
          trackIdx={this.state.trackIdx}
          playing={this.state.playing}
          queueElement={this.queueElement}
          getRequest={this.getRequest}
          putRequest={this.putRequest}
          postRequest={this.postRequest}
          fetchQueue={this.fetchQueue}
          getNext={this.getNext}
          getPrevious={this.getPrevious}
          changePlayingState={this.changePlayingState}
          fetchTrack={this.fetchTrack}
          likeSong={this.likeSong}
          unlikeSong={this.unlikeSong}
          loved={this.state.loved}
          changeLovedState={this.changeLovedState}
          data-testid="player-container"
        />
      </Fragment>
    );
  }
Example #25
Source File: SettingsForm.js    From apps-flashcard with MIT License 5 votes vote down vote up
export default function SettingsForm({setIsSettingsVisible, settings}) {
    return (
        <Box
            flex="none"
            display="flex"
            flexDirection="column"
            width="300px"
            backgroundColor="white"
            maxHeight="100vh"
            borderLeft="thick"
        >
            <Box
                flex="auto"
                display="flex"
                flexDirection="column"
                minHeight="0"
                padding={3}
                overflowY="auto"
            >
                <Heading marginBottom={3}>Settings</Heading>
                <FormField label="Table">
                    <TablePickerSynced globalConfigKey={ConfigKeys.TABLE_ID} />
                </FormField>
                {settings.table && (
                    <Fragment>
                        <FormField
                            label="View"
                            description="Only records in this view will be used"
                        >
                            <ViewPickerSynced
                                table={settings.table}
                                globalConfigKey={ConfigKeys.VIEW_ID}
                            />
                        </FormField>
                        <FormField label="Question field">
                            <FieldPickerSynced
                                table={settings.table}
                                globalConfigKey={ConfigKeys.QUESTION_FIELD_ID}
                            />
                        </FormField>
                        <FormField label="Answer field (optional)">
                            <FieldPickerSynced
                                table={settings.table}
                                shouldAllowPickingNone={true}
                                globalConfigKey={ConfigKeys.ANSWER_FIELD_ID}
                            />
                        </FormField>
                    </Fragment>
                )}
            </Box>
            <Box
                flex="none"
                display="flex"
                justifyContent="flex-end"
                paddingY={3}
                marginX={3}
                borderTop="thick"
            >
                <Button variant="primary" size="large" onClick={() => setIsSettingsVisible(false)}>
                    Done
                </Button>
            </Box>
        </Box>
    );
}
Example #26
Source File: index.js    From apps-url-preview with MIT License 5 votes vote down vote up
// Shows a preview, or a dialog that displays information about what
// kind of services (URLs) are supported by this app.
function RecordPreviewWithDialog({
    activeTable,
    selectedRecordId,
    selectedFieldId,
    setIsSettingsOpen,
}) {
    const [isDialogOpen, setIsDialogOpen] = useState(false);

    // Close the dialog when the selected record is changed.
    // The new record might have a preview, so we don't want to hide it behind this dialog.
    useEffect(() => {
        setIsDialogOpen(false);
    }, [selectedRecordId]);

    return (
        <Fragment>
            <Box
                position="absolute"
                top={0}
                left={0}
                right={0}
                bottom={0}
                display="flex"
                flexDirection="column"
                alignItems="center"
                justifyContent="center"
            >
                <RecordPreview
                    activeTable={activeTable}
                    selectedRecordId={selectedRecordId}
                    selectedFieldId={selectedFieldId}
                    setIsDialogOpen={setIsDialogOpen}
                    setIsSettingsOpen={setIsSettingsOpen}
                />
            </Box>
            {isDialogOpen && (
                <Dialog onClose={() => setIsDialogOpen(false)} maxWidth={400}>
                    <Dialog.CloseButton />
                    <Heading size="small">Supported services</Heading>
                    <Text marginTop={2}>Previews are supported for these services:</Text>
                    <Text marginTop={2}>
                        <Link
                            href="https://support.airtable.com/hc/en-us/articles/205752117-Creating-a-base-share-link-or-a-view-share-link"
                            target="_blank"
                        >
                            Airtable share links
                        </Link>
                        , Figma, SoundCloud, Spotify, Vimeo, YouTube, Loom share links, Google Drive
                        share links, Google Docs, Google Sheets, Google Slides
                    </Text>
                    <Link
                        marginTop={2}
                        href="https://airtable.com/shrQSwIety6rqfJZX"
                        target="_blank"
                    >
                        Request a new service
                    </Link>
                </Dialog>
            )}
        </Fragment>
    );
}
Example #27
Source File: index.js    From apps-wikipedia-enrichment with MIT License 5 votes vote down vote up
function WikipediaEnrichmentApp() {
    const base = useBase();

    const table = base.getTableByName(TABLE_NAME);
    const titleField = table.getFieldByName(TITLE_FIELD_NAME);

    // load the records ready to be updated
    // we only need to load the word field - the others don't get read, only written to.
    const records = useRecords(table, {fields: [titleField]});

    // keep track of whether we have up update currently in progress - if there is, we want to hide
    // the update button so you can't have two updates running at once.
    const [isUpdateInProgress, setIsUpdateInProgress] = useState(false);

    // check whether we have permission to update our records or not. Any time we do a permissions
    // check like this, we can pass in undefined for values we don't yet know. Here, as we want to
    // make sure we can update the summary and image fields, we make sure to include them even
    // though we don't know the values we want to use for them yet.
    const permissionCheck = table.checkPermissionsForUpdateRecord(undefined, {
        [EXTRACT_FIELD_NAME]: undefined,
        [IMAGE_FIELD_NAME]: undefined,
    });

    async function onButtonClick() {
        setIsUpdateInProgress(true);
        const recordUpdates = await getExtractAndImageUpdatesAsync(table, titleField, records);
        await updateRecordsInBatchesAsync(table, recordUpdates);
        setIsUpdateInProgress(false);
    }

    return (
        <Box
            // center the button/loading spinner horizontally and vertically.
            position="absolute"
            top="0"
            bottom="0"
            left="0"
            right="0"
            display="flex"
            flexDirection="column"
            justifyContent="center"
            alignItems="center"
        >
            {isUpdateInProgress ? (
                <Loader />
            ) : (
                <Fragment>
                    <Button
                        variant="primary"
                        onClick={onButtonClick}
                        disabled={!permissionCheck.hasPermission}
                        marginBottom={3}
                    >
                        Update summaries and images
                    </Button>
                    {!permissionCheck.hasPermission &&
                        // when we don't have permission to perform the update, we want to tell the
                        // user why. `reasonDisplayString` is a human-readable string that will
                        // explain why the button is disabled.
                        permissionCheck.reasonDisplayString}
                </Fragment>
            )}
        </Box>
    );
}
Example #28
Source File: Notifications.js    From tisn.app with GNU Affero General Public License v3.0 5 votes vote down vote up
Notifications = () => {
  const { t } = useTranslation();
  const style = Style();
  const notifications = useNotifications();

  const [regularNotifications, setRegularNotifications] = useState(null);
  const [regularReadNotifications, setRegularReadNotifications] = useState(
    null
  );
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (notifications) {
      setRegularNotifications(notifications.regular);
      setRegularReadNotifications(notifications.regularRead);
      setLoading(false);
    }
  }, [notifications]);

  const notificationsGrid = (notifications) => (
    <Grid container justify="center" spacing={2}>
      {notifications.map((notification) => (
        <Grid item key={notification._id} sm={6} xs={12}>
          {<NotificationCard notification={notification} />}
        </Grid>
      ))}
    </Grid>
  );

  return (
    <Fragment>
      {loading ? (
        <LinearProgress />
      ) : (
        <div className={style.root}>
          <Grid container direction="column" alignItems="center" spacing={2}>
            <Grid item>
              <Typography variant="h2">{t('notifications.title')}</Typography>
            </Grid>
            <Grid item>
              {regularNotifications && regularNotifications.length > 0 ? (
                notificationsGrid(regularNotifications)
              ) : (
                <Typography variant="body1">
                  {t('notifications.noNew')}
                </Typography>
              )}
            </Grid>
            {regularReadNotifications && regularReadNotifications.length > 0 && (
              <Grid item>
                <ExpansionPanel>
                  <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}>
                    {t('notifications.read')}
                  </ExpansionPanelSummary>
                  <ExpansionPanelDetails>
                    {notificationsGrid(regularReadNotifications)}
                  </ExpansionPanelDetails>
                </ExpansionPanel>
              </Grid>
            )}
          </Grid>
        </div>
      )}
    </Fragment>
  );
}
Example #29
Source File: MoveList.js    From TrelloClone with MIT License 5 votes vote down vote up
MoveList = ({ listId, closeMenu }) => {
  const classes = useStyles();
  const [openDialog, setOpenDialog] = useState(false);
  const [position, setPosition] = useState(0);
  const [positions, setPositions] = useState([0]);
  const lists = useSelector((state) => state.board.board.lists);
  const listObjects = useSelector((state) => state.board.board.listObjects);
  const dispatch = useDispatch();

  useEffect(() => {
    const mappedListObjects = listObjects
      .sort(
        (a, b) =>
          lists.findIndex((id) => id === a._id) - lists.findIndex((id) => id === b._id)
      )
      .map((list, index) => ({ list, index }));
    setPositions(
      mappedListObjects.filter((list) => !list.list.archived).map((list) => list.index)
    );
    setPosition(mappedListObjects.findIndex((list) => list.list._id === listId));
  }, [lists, listId, listObjects]);

  const onSubmit = async () => {
    dispatch(moveList(listId, { toIndex: position }));
    setOpenDialog(false);
    closeMenu();
  };

  return (
    <Fragment>
      <div onClick={() => setOpenDialog(true)}>Move This List</div>
      <Dialog open={openDialog} onClose={() => setOpenDialog(false)}>
        <div className={classes.moveListTop}>
          <DialogTitle>{'Move List'}</DialogTitle>
          <Button onClick={() => setOpenDialog(false)}>
            <CloseIcon />
          </Button>
        </div>
        <DialogActions className={classes.moveListBottom}>
          <FormControl>
            <InputLabel shrink>Position</InputLabel>
            <Select
              value={position}
              required
              onChange={(e) => setPosition(e.target.value)}
              displayEmpty
            >
              {positions.map((position, index) => (
                <MenuItem key={position} value={position}>
                  {index + 1}
                </MenuItem>
              ))}
            </Select>
            <Button
              type='submit'
              variant='contained'
              color='primary'
              className={classes.moveListButton}
              onClick={onSubmit}
            >
              Move List
            </Button>
          </FormControl>
        </DialogActions>
      </Dialog>
    </Fragment>
  );
}