@material-ui/core#GridListTile JavaScript Examples

The following examples show how to use @material-ui/core#GridListTile. 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: ModalPhotoContent.js    From AED-Map with MIT License 5 votes vote down vote up
ModalPhotoContent = ({
  images,
  handleClose,
  hidePopup,
  id
}) => {
  const classes = useStyles();
  const [, ShowAlert] = useAlert();
  const handleImageSend = async bodyFormData => {
    try {
      await createImage(bodyFormData, id);
      handleClose();
      hidePopup();
      ShowAlert({
        open: true,
        severity: 'success',
        message: 'Фотографії успішно додані'
      });
    } catch (error) {
      ShowAlert({
        open: true,
        severity: 'error',
        message:
          'Тимчасова серверна помилка. Спробуйте ще раз.'
      });
    }
  };
  return (
    <UploadImage
      handleImageSend={handleImageSend}
      handleClose={handleClose}
    >
      <Container className={classes.root} maxWidth="md">
        {images.length > 0 ? (
          <GridList
            cellHeight={180}
            className={classes.gridList}
          >
            <GridListTile
              key="Subheader"
              cols={2}
              style={{ height: 'auto' }}
            >
              <Typography variant="h5">
                Усі фотографії
              </Typography>
            </GridListTile>
            {images.map(image => (
              <GridListTile key={image.id}>
                <img
                  src={`${BASE_URL}/api/images/${image.filename}`}
                  alt={image.filename}
                />
              </GridListTile>
            ))}
          </GridList>
        ) : (
          <Typography variant="h5">
            Поки немає фотографій
          </Typography>
        )}
      </Container>
    </UploadImage>
  );
}
Example #2
Source File: contributors.js    From GSOD.Contributors_website with Mozilla Public License 2.0 5 votes vote down vote up
GetContributors = () => {
  const classes = useStyles();
  const [hasError, setErrors] = useState(false);
  const [contributors, setContributors] = useState([]);
  const [loading, setLoading] = useState(false)

  useEffect(() => {
       let mounted = true;
       setLoading(true)
       fetch("https://api.github.com/repos/moja-global/FLINT/contributors",
       {headers: { 'Authorization': 'Bearer '+process.env.REACT_APP_GITHUB_PERSONAL_ACCESS_TOKEN,}})
       .then(res => res.json()).then(
           res => {
             if(mounted && contributors.length == 0){
               setContributors(res);
               setLoading(false)
             console.log(contributors);}}
       ).catch(err => {
           setLoading(false)})
      return () => mounted = false;
   }, [contributors])

   return (
     <div className={classes.root}>
     <Grid container>
     <Grid xs={12}>
     <h1> All Contributors List</h1>
     <p> Contribute to Moja Global and get featured in this list!</p>
     </Grid>
     </Grid>
       <GridList cellHeight={160} className={classes.gridList} cols={4}>
         <GridListTile key="Subheader" cols={4} style={{ height: 'auto' }}>
           <ListSubheader component="div">All contributors</ListSubheader>
         </GridListTile>

               {contributors.map( contributor =>  (
                 <GridListTile key={contributor.id} >
                   <img src={contributor.avatar_url} alt={contributor.login} />
                   <GridListTileBar
                     title={contributor.login}
                     subtitle={<span>Contributions: {contributor.contributions}</span>}
                     actionIcon={
                       <IconButton href={contributor.url} aria-label={`info about ${contributor.login}`} className={classes.icon}>
                         <InfoIcon />
                       </IconButton>
                     }

                         />
                       </GridListTile>
                     ))
                   }

       </GridList>
     </div>
   );

      }
Example #3
Source File: HistorySection.js    From Quizzie with MIT License 4 votes vote down vote up
function HistorySection(props) {
	const [userType, setUserType] = useState(props.type);
	const [profile, setProfile] = useState(props.profile);
	const [quizzes, setQuizzes] = useState([]);

	const [loading, setLoading] = useState(true);

	const getCols = () => {
		if (isWidthUp('md', props.width)) {
			return 3;
		}

		return 2;
	}

	const getQuizzes = async () => {

		let token = localStorage.getItem("authToken");
		let url = null;

		if(userType === "admin") url = "https://quizzie-api.herokuapp.com/admin/created";
		else url = "https://quizzie-api.herokuapp.com/user/quizzesGiven";

		try {
			await axios.get(url, {
				headers: {
					"auth-token": token
				}
			}).then(res => {
				let quizL = res.data.result.sort(function(a,b) {return a.scheduledFor - b.scheduledFor});
				setQuizzes(quizL);
				setLoading(false);
			})
		} catch (error) {
			console.log(error);
			setLoading(false);
		}
	}

	useEffect(() => {
		getQuizzes();
	}, [])

	if (loading) {
		return (
			<QuizLoading />
		)
	}
	else if (userType === "admin") {
		return (
			<div className="history-section">
				{quizzes.length === 0 ?
					<p style={{ textAlign: 'center' }}>You have not created any quizzes yet!</p>
					:
					<GridList cols={getCols()} className="grid-list">
						{quizzes.map((quiz) => (
							<GridListTile key={quiz._id} className="quiz-tile">
								<img src="../CC LOGO-01.svg" />
								<GridListTileBar
									title={quiz.quizName}
									subtitle={`By: You`}
									actionIcon={
										<Tooltip title="Settings">
											<IconButton aria-label={`edit ${quiz.quizName}`}
												component={Link} to={`/editQuiz/${quiz._id}`}>
												<Settings className="enroll-icon" />
											</IconButton>
										</Tooltip>
									}
								/>
							</GridListTile>
						))}
					</GridList>
				}
			</div>
		)
	}
	else {
		return (
			<div className="history-section">
				{profile.quizzesGiven.length === 0 ?
					<p style={{ textAlign: 'center' }}>You have not given any quizzes yet!</p>
					: <List aria-label="quiz display" className="owner-quiz-list">
						{quizzes.map(quiz => (
							quiz.quizId !== null?
								(<ListItem button className="owner-quiz-item" component={Link} key={quiz._id} to={`/results/${quiz.quizId._id}`}>
									<ListItemText primary={quiz.quizId.quizName} secondary={`Scored: ${quiz.marks}`} />
									<ListItemSecondaryAction>
										<IconButton edge="end" aria-label="details" component={Link} to={`/results/${quiz.quizId._id}`}>
											<ArrowForwardIos />
										</IconButton>
									</ListItemSecondaryAction>
								</ListItem>): null
						))}
					</List>}
			</div>
		)
	}
}
Example #4
Source File: QuizzesSection.js    From Quizzie with MIT License 4 votes vote down vote up
function QuizzesSection(props) {
	const [loading, setLoading] = useState(true);
	const [userType, setUserType] = useState(props.type);
	const [profile, setProfile] = useState(props.profile);
	const [quizzes, setQuizzes] = useState([]);
	const [quizzesEnrolled, setQuizzesEnrolled] = useState([]);

	const [joinModal, setJoinModal] = useState(false);
	const [quizCode, setQuizCode] = useState("");
	const [quizCodeError, setQuizCodeError] = useState(false);

	const [enrollModal, setEnrollModal] = useState(false);
	const [enrollQuizName, setEnrollQuiz] = useState("");
	const [enrollQuizId, setEnrollQuizId] = useState("");

	const [enrollSnack, setEnrollSnack] = useState(false);
	const [snackbar, setSnackBar] = useState(false);
	const [errorSnack, setErrorSnack] = useState(false);

	const [infoModal, setInfoModal] = useState(false);
	const [infoLoading, setInfoLoading] = useState(false);
	const [currQuiz, setCurrQuiz] = useState({});
	const [timeRemain, setTimeRemain] = useState("");

	const [startModal, setStartModal] = useState(false);
	const [quizStarted, setQuizStarted] = useState(false);
	const [redirectId, setRedirectId] = useState("");
	const [quizDetails, setQuizDetails] = useState({});

	const [earlyError, setEarlyError] = useState(false);
	const [lateError, setLateError] = useState(false);
	const [givenSnack, setGivenSnack] = useState(false);
	const [privateWrongCode, setPrivateWrongCode] = useState(false);
	const [alreadyEnrolled, setAlreadyEnrolled] = useState(false);

	const setRefresh = props.refresh;

	const { executeRecaptcha } = useGoogleReCaptcha();

	const getCols = () => {
		if (isWidthUp("md", props.width)) {
			return 3;
		}

		return 2;
	};

	const getInfoWidth = () => {
		if (isWidthUp("sm", props.width)) {
			return "45%";
		}

		return "80%";
	};

	const onCloseHandle = () => {
		setJoinModal(false);
		setInfoModal(false);
		setStartModal(false);

		setQuizCode("");
		setQuizCodeError(false);
		setEnrollModal(false);
		setEnrollQuiz("");
		setEnrollQuizId("");
		setTimeRemain("");
		setCurrQuiz({});
	};

	const onJoinClick = () => {
		setJoinModal(true);
	};

	const handleJoinChange = (event) => {
		setQuizCode(event.target.value);
	};

	const handleEnrollButton = (quiz) => {
		setEnrollQuiz(quiz.quizName);
		setEnrollQuizId(quiz._id);
		setEnrollModal(true);
	};

	const handleInfoButton = (quiz) => {
		setInfoModal(true);
		getQuizInfo(quiz.quizId._id);
	};

	const handleStartButton = (quiz) => {
		setEnrollQuiz(quiz.quizId.quizName);
		setEnrollQuizId(quiz.quizId._id);
		setStartModal(true);
	};

	const getQuizInfo = async (id) => {
		setInfoLoading(true);

		let token = localStorage.getItem("authToken");
		let url = `https://quizzie-api.herokuapp.com/quiz/${id}`;

		try {
			await axios
				.get(url, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setCurrQuiz(res.data.result);
					setInfoLoading(false);
				});
		} catch (error) {
			console.log(error);
			onCloseHandle();
			setInfoLoading(false);
		}
	};

	const handleJoinSubmit = async () => {
		if (quizCode.trim().length === 0) {
			setQuizCodeError(true);
			return;
		}
		setQuizCodeError(false);
		setEnrollSnack(true);
		let url = "https://quizzie-api.herokuapp.com/quiz/enrollPrivate";
		let token = localStorage.getItem("authToken");

		let captcha = await executeRecaptcha("join_private");

		let data = {
			quizCode: quizCode,
			captcha: captcha,
		};

		try {
			await axios
				.patch(url, data, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setRefresh(true);
					onCloseHandle();
					setSnackBar(true);
				});
		} catch (error) {
			setEnrollSnack(false);
			if (error.response.status === 404) {
				setPrivateWrongCode(true);
			} else if (error.response.status === 409) {
				setAlreadyEnrolled(true);
			} else {
				setErrorSnack(true);
			}
		}
	};

	const handleEnroll = async () => {
		setEnrollSnack(true);
		let token = localStorage.getItem("authToken");
		let url = "https://quizzie-api.herokuapp.com/quiz/enroll";

		let captcha = await executeRecaptcha("quiz_enroll");

		let data = {
			quizId: enrollQuizId,
			captcha: captcha,
		};

		try {
			await axios
				.patch(url, data, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setRefresh(true);
					onCloseHandle();
					setSnackBar(true);
				});
		} catch (error) {
			console.log(error);
			setErrorSnack(true);
		}
	};

	const handleUnenroll = async () => {
		setEnrollSnack(true);
		let token = localStorage.getItem("authToken");
		let url = "https://quizzie-api.herokuapp.com/quiz/unenroll";

		let captcha = await executeRecaptcha("quiz_unenroll");

		let data = {
			quizId: currQuiz._id,
			captcha: captcha,
		};

		try {
			await axios
				.patch(url, data, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setRefresh(true);
				});
		} catch (error) {
			console.log(error);
			setErrorSnack(true);
		}
	};

	const handleQuizStart = async () => {
		setEnrollSnack(true);
		let token = localStorage.getItem("authToken");
		let url = `https://quizzie-api.herokuapp.com/quiz/start`;

		let captcha = await executeRecaptcha("quiz_start");

		let data = {
			quizId: enrollQuizId,
			captcha: captcha,
		};

		try {
			await axios
				.patch(url, data, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setRedirectId(data.quizId);
					setQuizDetails(res.data);
					setQuizStarted(true);
				});
		} catch (error) {
			setEnrollSnack(false);
			if (error.response.status === 401) {
				setEarlyError(true);
			} else if (error.response.status === 402) {
				setLateError(true);
			} else if (error.response.status === 405) {
				setGivenSnack(true);
			}
		}
	};

	const setupEnrolled = () => {
		let quizzes = [];

		profile.quizzesEnrolled.map((quiz) => {
			if (
				!profile.quizzesGiven.find((o) => o.quizId === quiz.quizId._id)
			) {
				quizzes.push(quiz);
			}
		});

		setQuizzesEnrolled(quizzes);
	};

	const getQuizzes = async () => {
		setLoading(true);
		let token = localStorage.getItem("authToken");
		let url = "https://quizzie-api.herokuapp.com/quiz/all";

		let quizList = [];

		try {
			await axios
				.get(url, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					res.data.result.map((quiz) => {
						if (quiz.quizType === "public") {
							if (userType === "user") {
								if (
									!profile.quizzesEnrolled.find(
										(o) => o.quizId._id === quiz._id
									)
								)
									quizList.push(quiz);
							} else quizList.push(quiz);
						}
					});

					quizList.sort(function (a, b) {
						return a.scheduledFor - b.scheduledFor;
					});

					setQuizzes(quizList);
					setLoading(false);
				});
		} catch (error) {
			console.log(error);
		}
	};

	useEffect(() => {
		if (infoModal) {
			if (currQuiz.scheduledFor <= Date.now()) {
				setTimeRemain("Already Started!");
			} else {
				setTimeout(() => {
					setTimeRemain(
						countdown(
							new Date(),
							new Date(Number(currQuiz.scheduledFor))
						).toString()
					);
				}, 1000);
			}
		}
	});

	useEffect(() => {
		if (userType === "user") setupEnrolled();
		getQuizzes();
	}, []);

	if (loading) {
		return <QuizLoading />;
	} else if (quizStarted) {
		return (
			<Redirect
				to={{
					pathname: `/quiz`,
					state: {
						questions: quizDetails.data,
						duration: quizDetails.duration,
						start: quizDetails.scheduledFor,
						id: enrollQuizId,
						timeStarted: Date.now(),
						restartStatus: quizDetails.quizRestart,
					},
				}}
			/>
		);
	} else {
		return (
			<div className="quizzes-section">
				<div className="quiz-btn-section">
					{userType === "user" ? (
						<Button className="join-quiz-btn" onClick={onJoinClick}>
							<Check />
							Join a Quiz
						</Button>
					) : null}
					{userType === "admin" ? (
						<Button
							className="create-quiz-btn"
							component={Link}
							to="/createQuiz"
						>
							<Add />
							Create a quiz
						</Button>
					) : null}
				</div>
				{userType === "user" ? (
					<div className="enrolled-list">
						<Typography variant="h5" className="up-quizzes">
							Enrolled Quizzes
						</Typography>
						{quizzesEnrolled.length === 0 ? (
							<p style={{ textAlign: "center" }}>
								Sorry! No quizzes available at the moment!
							</p>
						) : (
							<div className="quiz-list root1">
								<GridList
									cols={getCols()}
									className="grid-list btn-set"
								>
									{quizzesEnrolled.map((quiz) => (
										<GridListTile
											key={quiz._id}
											className="quiz-tile"
										>
											<img src="../CC LOGO-01.svg" />
											<GridListTileBar
												title={quiz.quizId.quizName}
												actionIcon={
													<div className="inline">
														<Tooltip title="Start Quiz">
															<IconButton
																aria-label={`start ${quiz.quizId.quizName}`}
																onClick={() =>
																	handleStartButton(
																		quiz
																	)
																}
															>
																<PlayCircleFilled className="enroll-icon" />
															</IconButton>
														</Tooltip>
														<Tooltip title="Info">
															<IconButton
																aria-label={`info ${quiz.quizId.quizName}`}
																onClick={() =>
																	handleInfoButton(
																		quiz
																	)
																}
															>
																<Info className="enroll-icon" />
															</IconButton>
														</Tooltip>
													</div>
												}
											/>
										</GridListTile>
									))}
								</GridList>
							</div>
						)}
					</div>
				) : null}
				<Typography variant="h5" className="up-quizzes">
					Upcoming Quizzes
				</Typography>
				{quizzes.length === 0 ? (
					<p style={{ textAlign: "center" }}>
						Sorry! No quizzes available at the moment!
					</p>
				) : (
					<div className="quiz-list root1">
						<GridList cols={getCols()} className="grid-list">
							{quizzes.map((quiz) => (
								<GridListTile
									key={quiz._id}
									className="quiz-tile"
								>
									<img src="../CC LOGO-01.svg" />
									<GridListTileBar
										title={quiz.quizName}
										subtitle={`By: ${quiz.adminId.name}`}
										actionIcon={
											userType === "user" ? (
												<Tooltip title="Enroll">
													<IconButton
														aria-label={`enroll ${quiz.quizName}`}
														onClick={() =>
															handleEnrollButton(
																quiz
															)
														}
													>
														<Check className="enroll-icon" />
													</IconButton>
												</Tooltip>
											) : null
										}
									/>
								</GridListTile>
							))}
						</GridList>
					</div>
				)}
				<Dialog
					open={joinModal}
					onClose={onCloseHandle}
					aria-labelledby="join-quiz-modal"
					PaperProps={{
						style: {
							backgroundColor: "white",
							color: "#333",
							minWidth: "30%",
						},
					}}
					style={{ width: "100%" }}
				>
					<div className="modal-info">
						{userType === "admin" ? (
							<Typography
								variant="h6"
								className="type-head join-sub"
							>
								Organizers cannot enroll in quizzes.
							</Typography>
						) : (
							<div
								style={{
									display: "flex",
									flexDirection: "column",
								}}
							>
								<Typography variant="h5" className="type-head">
									JOIN A PRIVATE QUIZ
								</Typography>
								<Typography
									variant="h6"
									className="type-head join-sub"
								>
									Enter the code of the quiz you want to join
								</Typography>
								<TextInput
									error={quizCodeError}
									helperText={
										quizCodeError ? "Required" : null
									}
									label="Quiz Code"
									variant="outlined"
									value={quizCode}
									onChange={handleJoinChange}
									className="quiz-code-field"
								/>
								<Button
									className="join-quiz-btn join-modal-btn"
									onClick={handleJoinSubmit}
								>
									Join!
								</Button>
							</div>
						)}
					</div>
				</Dialog>
				<Dialog
					open={enrollModal}
					onClose={onCloseHandle}
					aria-labelledby="enroll-quiz-modal"
					PaperProps={{
						style: {
							backgroundColor: "white",
							color: "#333",
							minWidth: "30%",
						},
					}}
					style={{ width: "100%" }}
				>
					<div className="modal-info">
						{userType === "admin" ? (
							<Typography
								variant="h6"
								className="type-head join-sub"
							>
								Organizers cannot enroll in quizzes.
							</Typography>
						) : (
							<div>
								<Typography
									variant="h6"
									className="type-head join-sub"
								>{`Are you sure you want to join ${enrollQuizName}?`}</Typography>
								<div className="btn-div m-top">
									{/* classes in Navbar.css */}
									<Button
										className="logout-btn m-right"
										onClick={handleEnroll}
									>
										Yes
									</Button>
									<Button
										className="cancel-btn m-left"
										onClick={onCloseHandle}
									>
										No
									</Button>
								</div>
							</div>
						)}
					</div>
				</Dialog>
				<Dialog
					open={startModal}
					onClose={onCloseHandle}
					aria-labelledby="start-quiz-modal"
					PaperProps={{
						style: {
							backgroundColor: "white",
							color: "#333",
							minWidth: "30%",
						},
					}}
					style={{ width: "100%" }}
				>
					<div className="modal-info">
						<div>
							<Typography
								variant="h6"
								className="type-head join-sub"
							>{`Are you sure you want to start ${enrollQuizName}?`}</Typography>
							<div className="btn-div m-top2 start-div">
								{/* classes in Navbar.css */}
								<Button
									className="logout-btn m-right"
									onClick={handleQuizStart}
								>
									Yes
								</Button>
								<Button
									className="cancel-btn m-left"
									onClick={onCloseHandle}
								>
									No
								</Button>
							</div>
						</div>
					</div>
				</Dialog>
				<Dialog
					open={infoModal}
					onClose={onCloseHandle}
					aria-labelledby="info-quiz-modal"
					PaperProps={{
						style: {
							backgroundColor: "white",
							color: "#333",
							minWidth: getInfoWidth(),
							maxHeight: "45%",
						},
					}}
					style={{ width: "100%" }}
				>
					<DialogTitle
						style={{ textAlign: "center", fontWeight: "bold" }}
					>
						Quiz Info
					</DialogTitle>

					{/* From the profile section */}
					{infoLoading ? (
						<Loading />
					) : (
						<div
							className="modal-info no-p-top"
							style={{ textAlign: "center" }}
						>
							<Typography
								variant="h6"
								className="profile-param info-param"
							>
								Name:{" "}
								<span className="profile-data">
									{currQuiz.quizName}
								</span>
							</Typography>
							<Typography
								variant="h6"
								className="profile-param info-param"
							>
								Date:{" "}
								<span className="profile-data">
									{new Date(
										Number(currQuiz.scheduledFor)
									).toDateString()}
								</span>
							</Typography>
							<Typography
								variant="h6"
								className="profile-param info-param"
							>
								Time:{" "}
								<span className="profile-data">
									{new Date(
										Number(currQuiz.scheduledFor)
									).toLocaleTimeString()}
								</span>
							</Typography>
							<div className="time-sec">
								<Typography
									variant="h6"
									className="profile-param info-param"
								>
									<span className="profile-data time-rem">
										{timeRemain}
									</span>
								</Typography>
							</div>
							<Button
								className="unenroll-btn"
								onClick={handleUnenroll}
							>
								<Block style={{ color: "white" }} />
								Unenroll
							</Button>
						</div>
					)}
				</Dialog>
				<Snackbar
					open={snackbar}
					autoHideDuration={2000}
					onClose={() => setSnackBar(false)}
				>
					<Alert
						variant="filled"
						severity="success"
						onClose={() => setSnackBar(false)}
					>
						Successfully Enrolled!
					</Alert>
				</Snackbar>
				<Snackbar
					open={errorSnack}
					autoHideDuration={2000}
					onClose={() => setErrorSnack(false)}
				>
					<Alert
						variant="filled"
						severity="error"
						onClose={() => setErrorSnack(false)}
					>
						There was some error. Please try again!
					</Alert>
				</Snackbar>
				<Snackbar
					open={enrollSnack}
					autoHideDuration={5000}
					onClose={() => setEnrollSnack(false)}
				>
					<Alert
						variant="filled"
						severity="info"
						onClose={() => setErrorSnack(false)}
					>
						Processing... Please Wait!
					</Alert>
				</Snackbar>
				<Snackbar
					open={earlyError}
					autoHideDuration={5000}
					onClose={() => setEarlyError(false)}
				>
					<Alert
						variant="filled"
						severity="error"
						onClose={() => setEarlyError(false)}
					>
						The quiz has not yet started!
					</Alert>
				</Snackbar>
				<Snackbar
					open={lateError}
					autoHideDuration={5000}
					onClose={() => setLateError(false)}
				>
					<Alert
						variant="filled"
						severity="error"
						onClose={() => setLateError(false)}
					>
						This quiz has ended!
					</Alert>
				</Snackbar>
				<Snackbar
					open={givenSnack}
					autoHideDuration={5000}
					onClose={() => setGivenSnack(false)}
				>
					<Alert
						variant="filled"
						severity="error"
						onClose={() => setGivenSnack(false)}
					>
						Already given this quiz!
					</Alert>
				</Snackbar>
				<Snackbar
					open={privateWrongCode}
					autoHideDuration={5000}
					onClose={() => setPrivateWrongCode(false)}
				>
					<Alert
						variant="filled"
						severity="error"
						onClose={() => setPrivateWrongCode(false)}
					>
						This quiz code does not exists!
					</Alert>
				</Snackbar>
				<Snackbar
					open={alreadyEnrolled}
					autoHideDuration={5000}
					onClose={() => setAlreadyEnrolled(false)}
				>
					<Alert
						variant="filled"
						severity="error"
						onClose={() => setAlreadyEnrolled(false)}
					>
						Already enrolled in this quiz!
					</Alert>
				</Snackbar>
			</div>
		);
	}
}
Example #5
Source File: index.js    From AED-Map with MIT License 4 votes vote down vote up
UploadImage = ({
  handleImageSend,
  children,
  user,
  defItemInfo
}) => {
  const classes = useStyles();
  const [images, setImages] = useState([]);
  const [
    permissionForAddImages,
    changePermissionForAddImages
  ] = useState(false);
  useEffect(() => {
    const permissionToAddImages = permissionService(
      ADD_IMAGES,
      user,
      defItemInfo
    );
    changePermissionForAddImages(permissionToAddImages);
  }, [user, defItemInfo]);

  const handleUpload = event => {
    const files = [...event.target.files];
    if (!files.length) return;
    setImages(prevImages =>
      uniqueArray([...prevImages, ...files], 'name')
    );
  };
  const removeImage = name => {
    setImages(prevImages =>
      prevImages.filter(image => image.name !== name)
    );
  };

  const sendImages = () => {
    const bodyFormData = new FormData();
    images.forEach(image =>
      bodyFormData.append('images', image)
    );
    handleImageSend(bodyFormData);
    setImages([]);
  };

  return (
    <Container className={classes.root} maxWidth="md">
      {images.length > 0 ? (
        <>
          <GridList
            cellHeight={240}
            className={classes.gridList}
          >
            <GridListTile
              key="Subheader"
              cols={2}
              style={{ height: 'auto' }}
            >
              <Typography variant="h5">
                Вибрані фотографії
              </Typography>
            </GridListTile>
            {images.map(image => {
              const src = URL.createObjectURL(image);
              const { name } = image;
              return (
                <GridListTile key={name}>
                  <img
                    src={src}
                    alt={name}
                    className={classes.imgPreview}
                    title="Подвійний клік видаляє фото"
                    onDoubleClick={() => removeImage(name)}
                  />

                  <GridListTileBar title={name} />
                </GridListTile>
              );
            })}
          </GridList>
          <Button
            className={classes.addBtn}
            variant="contained"
            color="primary"
            onClick={sendImages}
          >
            Загрузити фото
          </Button>
          <Typography component="h3">
            {`Загружено ${images.length} фото`}
          </Typography>
        </>
      ) : (
        <>{children}</>
      )}
      {permissionForAddImages && (
        <UploadButton
          htmlFor="add-photo"
          handleUpload={handleUpload}
        >
          {images.length > 0
            ? 'Добавити ще одне фото'
            : 'Добавити фото'}
        </UploadButton>
      )}
    </Container>
  );
}
Example #6
Source File: MapResults.js    From willow-grandstack with Apache License 2.0 4 votes vote down vote up
export default function MapResults(props) {
  console.log(props.properties)
  const theme = useTheme()

  const [onStarHandler, { data, loading, error }] = useMutation(gql`
    mutation starPropertyMutation($id: ID!) {
      starProperty(id: $id) {
        id
        address
      }
    }
  `)

  const style = {
    padding: '4px',
    color: '#fff',
    cursor: 'pointer',
    background: '#1978c8',
    borderRadius: '50%',
  }

  const useStyles = makeStyles((theme) => ({
    root: {
      display: 'flex',
    },
    paper: {
      padding: theme.spacing(2),
      display: 'flex',
      overflow: 'auto',
      flexDirection: 'column',
    },
    fixedHeight: {
      height: 540,
    },
  }))
  const classes = useStyles(theme)
  const fixedHeightPaper = clsx(classes.paper, classes.fixedHeight)

  const [viewport, setViewport] = useState({
    latitude: 45.667397,
    longitude: -111.054718,
    zoom: 13,
  })

  const [currentProperty, setCurrentProperty] = useState(props.properties[0])

  return (
    <React.Fragment>
      <Grid container spacing={4}>
        <Grid item xs={12} md={2} lg={2}>
          <Paper className={fixedHeightPaper}>
            <StarredProperties />
          </Paper>
        </Grid>
        <Grid item xs={12} md={7} lg={6}>
          <Paper className={fixedHeightPaper}>
            <MapGL
              style={{ width: '100%', height: '100%' }}
              mapStyle="mapbox://styles/mapbox/light-v9"
              accessToken={process.env.REACT_APP_MAPBOX_TOKEN}
              latitude={viewport.latitude}
              longitude={viewport.longitude}
              zoom={viewport.zoom}
              onViewportChange={setViewport}
            >
              {props.properties.map((p, i) => {
                return (
                  <Marker
                    key={i}
                    longitude={p.location.longitude}
                    latitude={p.location.latitude}
                  >
                    <div
                      onClick={() => setCurrentProperty(p)}
                      style={style}
                    ></div>
                  </Marker>
                )
              })}
            </MapGL>
          </Paper>
        </Grid>
        <Grid item xs={12} md={3} lg={4}>
          <Paper className={fixedHeightPaper}>
            <p>{currentProperty.address}</p>
            <Button
              onClick={() =>
                onStarHandler({ variables: { id: currentProperty.id } })
              }
            >
              Star Property
            </Button>
            <ul>
              <li>Square feet: {currentProperty.sqft}</li>
              <li>Bedrooms: {currentProperty.bedrooms}</li>
              <li>Full baths: {currentProperty.full_baths}</li>
              <li>Half baths: {currentProperty.half_baths}</li>
            </ul>
            <GridList cellHeight={160} cols={2}>
              {currentProperty.photos.map((v, i) => (
                <GridListTile key={i} cols={1}>
                  <img src={v.url}></img>
                </GridListTile>
              ))}
            </GridList>
          </Paper>
        </Grid>
      </Grid>
    </React.Fragment>
  )
}