react-router-dom#useHistory JavaScript Examples
The following examples show how to use
react-router-dom#useHistory.
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: use-navigation.js From MDXP with MIT License | 6 votes |
useNavigation = () => {
const history = useHistory();
const root = useRoot();
const deck = useDeck();
return {
next: () => {
next(history, root, deck);
},
previous: () => {
previous(history, root, deck);
},
nextSlide: (step = 0) => {
nextSlide(history, root, deck, step);
},
previousSlide: (step = 0) => {
previousSlide(history, root, deck, step);
},
navigate: ({slide, step = 0, mode, replace = false}) => {
navigate(history, root, {mode, slide, step, replace});
},
setMode: mode => {
setMode(history, root, deck, mode);
}
};
}
Example #2
Source File: _Index.js From acy-dex-interface with MIT License | 6 votes |
BuyGlp = () => {
const { chainId } = useWeb3React();
const history = useHistory()
const [isBuying, setIsBuying] = useState(true)
useEffect(() => {
const hash = history.location.hash.replace('#', '')
const buying = !(hash === 'redeem')
setIsBuying(buying)
}, [history.location.hash])
return (
<PageHeaderWrapper>
<div className={styles.main}>
<div className={styles.titleblock}>
<h3>
<AcyIcon.MyIcon width={30} type="arrow" />
<span className={styles.span}>Buy / Sell GLP</span>
</h3>
<div className={styles.subtitle}>
Purchase GLP tokens to earn {chainId === POLYGON ? 'MATIC' : 'BNB'} fees from swaps and leverages trading.<br />Note that there is a minimum holding time of 15 minutes after a purchase.<br />
</div>
</div>
<GlpSwap isBuying={isBuying} setIsBuying={setIsBuying} />
</div>
</PageHeaderWrapper>
);
}
Example #3
Source File: ProviderCard.js From akashlytics-deploy with GNU General Public License v3.0 | 6 votes |
export function ProviderCard({ provider, leases }) {
const classes = useStyles();
const history = useHistory();
const cardClick = () => {
history.push(UrlService.providerDetail(provider.owner))
}
return (
<Grid item xs={12}>
<Paper elevation={1} className={classes.root} onClick={cardClick}>
<ProviderSummary provider={provider} leases={leases} />
</Paper>
</Grid >
);
}
Example #4
Source File: AuthContext.js From Realtime-Chat-Application-ReactJs with MIT License | 6 votes |
AuthProvider = ({ children }) => {
const [loading, setLoading] = useState(true);
const [user, setUser] = useState(null);
const history = useHistory();
//this is the main clas for authentication
useEffect(() => {
auth.onAuthStateChanged((user) => {
setUser(user);
setLoading(false);
if (user) history.push("/chats");
});
}, [user, history]);
const value = { user };
return (
<AuthContext.Provider value={value}>
{!loading && children}
</AuthContext.Provider>
);
}
Example #5
Source File: SaveRoutePage.js From viade_en2b with MIT License | 6 votes |
SaveRoutePage=()=> {
// this.props.showUpload();
let history = useHistory();
function toDo(params) { //EJEMPLO DE FUNCIÓN PARA PASARLE AL onUpload
history.push('/routes');
cache.default.setReload(true);
}
function emptyTrigger(){
//Function To Trigger
}
return (
<React.Fragment>
<BurgerMenu pageWrapId="page-wrap" container="outer-container" />
<div className="savePage" id="page-wrap">
<div className="cardsave">
<SaveRoute onFinish={toDo} />
<div
className="mapContainerSave"
style={{ position: "relative", width: "40vw", height: "40vh" }}
>
<MapContainer />
</div>
</div>
</div>
</React.Fragment>
)
}
Example #6
Source File: Search.js From Merch-Dropper-fe with MIT License | 6 votes |
Search = (props) => {
const history = useHistory();
const [searchValue, setSearchValue] = useState("");
const handleSearchInput = e => {
setSearchValue(e.target.value);
};
const resetInputField = e => {
setSearchValue('');
};
const callSearchFunction = e => {
e.preventDefault();
props.searchStoreName(searchValue);
resetInputField();
history.push('/products')
};
return (
<Form className='search'>
<Input
value={searchValue}
onChange={handleSearchInput}
type='text'
placeholder='Store Name'
/>
<Button onClick={callSearchFunction}>
<i class="fa fa-search"></i>
</Button>
</Form>
)
}
Example #7
Source File: PersonInfo.js From foster-together-fe with MIT License | 6 votes |
export default function Filter(props) {
const history = useHistory();
const [selected, setSelected] = useState("v");
useEffect(() => {
setSelected(props.selected);
}, [props]);
return (
<InfoContainer>
<InfoDiv>
<UserName>
{selected.first_name} {selected.last_name}{" "}
{selected.name !== undefined ? (
<SmallIcon
onClick={() => history.push(`/${selected.type}/${selected.id}`)}
src={require("../mapicons/redirect.png")}
/>
) : null}{" "}
</UserName>
<IconContain>
<InfoType>{selected.type}</InfoType>
</IconContain>
<SubInfoContainer>
<IconContain>
<Icon src={require("../mapicons/Address.svg")} />
<InfoText>{selected.address}</InfoText>
</IconContain>
<IconContain>
<Icon src={require("../mapicons/Email.svg")} />
<InfoText>{selected.email}</InfoText>
</IconContain>
<IconContain>
<Icon src={require("../mapicons/Phone.svg")} />
<InfoText>{selected.phone}</InfoText>
</IconContain>
</SubInfoContainer>
</InfoDiv>
</InfoContainer>
);
}
Example #8
Source File: AccountEventCard.js From neighborhood-chef-fe with MIT License | 6 votes |
AccountEVentCard = ({ event }) => {
const history = useHistory();
const classes = cardStyles();
const timeObject = parseTime(event.startTime);
const photo =
event.photo !== "null"
? event.photo
: chooseDefaultPicture(event.category_id);
const attending = event.users
? event.users.filter((event) => event.status === "Going")
: null;
return (
<>
<Card
onClick={() => {
history.push(`/events/${event.id}`);
history.go();
}}
className={classes.accountEvent}
>
<CardMedia
style={{ maxHeight: 100 }}
component="img"
src={photo}
title="Event Photo"
/>
<Typography variant="h6" style={{ fontWeight: "bold" }}>
{event.title}
</Typography>
<Typography>{`${attending.length || "0"} attending`}</Typography>
<Typography>{timeObject.commentTime}</Typography>
</Card>
</>
);
}
Example #9
Source File: Form.js From schematic-capture-fe with MIT License | 6 votes |
CreateNewProject = () => {
const { handleSubmit, register } = useForm();
const params = useParams();
const dispatch = useDispatch();
const history = useHistory();
const onAddNewProject = (data) => {
dispatch(addNewProject(data, params.id, history));
};
return (
<div>
<form onSubmit={handleSubmit(onAddNewProject)}>
<p>Please enter the project name below:</p>
<div>
{/*<form onSubmit={handleSubmit(onAddNewProject)}>*/}
{/* <StyledFields fields={schema} register={register} errors={errors} />*/}
{/* <button type="submit">Save</button>*/}
{/* <Link to={`/client/${params.id}`}>Cancel</Link>*/}
{/*</form>*/}
<input
type="string"
name="name"
id="name"
placeholder="Project Name"
aria-label="Project Name"
ref={register({ required: true })}
/>
</div>
<div>
<button variant="primary" submit="button" btnBlock>
Create
</button>
</div>
</form>
</div>
);
}
Example #10
Source File: App.js From social-media-strategy-fe with MIT License | 6 votes |
function App(props) {
initializeAnalytics();
const { authService } = useOktaAuth();
const dispatch = useDispatch();
const history = useHistory();
const location = useLocation();
const user = useSelector((state) => state.user);
useEffect(() => {
if (location.pathname === "/connect/twitter/callback") return;
if (!user.initialized) {
dispatch(initializeUser(authService, history));
return;
}
// eslint-disable-next-line
}, [user, location]);
return (
<Switch>
<Route exact path="/login" component={LoginOkta} />
<Route path="/implicit/callback" component={LoginCallback} />
<Route>
<NavMenuTemplate>
<SecureRoute path="/home" component={Home} />
<SecureRoute path="/analytics" component={Analytics} />
<SecureRoute path="/connect" component={ConnectAccounts} />
</NavMenuTemplate>
</Route>
</Switch>
);
}
Example #11
Source File: CategoryGrid.jsx From trashpanda-fe with MIT License | 6 votes |
CategoryGrid = ({ searchFocus }) => {
const history = useHistory();
const categories = useQuery(GET_CATEGORIES);
const handleCategoryClick = id => {
history.push(`/category/${id}`);
};
return (
<>
{categories && categories.loading && <Spinner />}
{categories && !categories.loading && (
<GridContainer searchFocus={searchFocus}>
{categories.data.families.map((category, key) => (
<GridCard
image={
category.image_url.length > 0
? category.image_url
: placeholderImg
}
name={category.description}
key={key}
onClick={() => handleCategoryClick(category.family_id)}
/>
))}
</GridContainer>
)}
</>
);
}
Example #12
Source File: GoogleRedirect.js From video-journal-for-teams-fe with MIT License | 6 votes |
GoogleRedirect = () => {
const { authService, authState } = useOktaAuth();
const history = useHistory();
const dispatch = useDispatch();
const oktaAuth = new OktaAuth({
issuer: "https://dev-292346.okta.com/oauth2/v1/default/",
idps: [{ type: "GOOGLE", id: "0oachck23hRb17ea34x6" }],
responseType: "id_token",
});
useEffect(() => {
console.log(window.location.href.split("="));
authService.getUser().then((user) => console.log(user));
history.push("/user-dashboard");
});
return <div></div>;
}
Example #13
Source File: Dashboard.js From workout-tracker-fe-pt with MIT License | 6 votes |
Dashboard = () => {
const history = useHistory();
return (
<div>
<NavCircle className="container">
<MobileNav />
</NavCircle>
<div>
<NavigationBar />
<WelcomeDashboard />
</div>
<DashboardAlignment>
<LogoContainer>
<Logo>
Fit<LogoText>Tracker</LogoText>
</Logo>
</LogoContainer>
</DashboardAlignment>
</div>
);
}
Example #14
Source File: DeletionDialog.jsx From Corona-tracker with MIT License | 6 votes |
DeletionDialog = props => {
const { userSession } = useBlockstack();
const { deleteObservations, deleteDetailData, setShowDeletionDialog, setReminderStatus } = props;
const history = useHistory();
const classes = useStyles();
return (
<div>
<Dialog open aria-describedby="disclaimer">
<DialogTitle align="center" id="alert-dialog-title">
<object title="logo" className={classes.logo} data={Logo} type="image/svg+xml" />
<object title="logoText" className={classes.textLogo} data={TextLogo} type="image/svg+xml" />
</DialogTitle>
<DialogContent>
<DialogContent align="left" id="disclaimer-text">
<DialogContentText>Are you sure you want to delete all of your observation data?</DialogContentText>
</DialogContent>
<DialogActions>
<Button
variant="outlined"
onClick={() => {
deleteObservations(userSession);
deleteDetailData();
window.localStorage.setItem('surveyCompleted', 'false');
setReminderStatus(true);
history.push('/');
}}
>
Yes
</Button>
<Button variant="outlined" onClick={() => setShowDeletionDialog(false)}>
No
</Button>
</DialogActions>
</DialogContent>
</Dialog>
</div>
);
}
Example #15
Source File: LogoutPage.js From app with MIT License | 6 votes |
function LogoutPage() {
const classes = useStyles();
const auth = useAuth();
const history = useHistory();
useEffect(() => {
auth.signOut().then(() => {
history.replace('/');
});
}, [auth, history]);
return (
<Container maxWidth="md">
<Helmet>
<title>Logging Out</title>
</Helmet>
<Paper className={classes.paper}>
<Typography
variant="h5"
align="center"
color="textPrimary"
gutterBottom>
Logging out...
</Typography>
<LinearProgress />
</Paper>
</Container>
);
}
Example #16
Source File: Nav.jsx From genshin with MIT License | 6 votes |
Nav = () => {
const element = useSelector(getElementData);
const CurrentElement = elements.find(({ name }) => element === name);
const history = useHistory();
const handleClick = () => {
history.push('/');
};
return (
<nav>
{CurrentElement && (
<CurrentElement.Component
className="logo"
size="40"
color={CurrentElement.color}
onClick={handleClick}
/>
)}
<NavLink exact to="/">
Home
</NavLink>
<NavLink to="/guides">Guides</NavLink>
<NavLink to="/dailies">Dailies</NavLink>
<NavLink to="/indispensables">Indispensables</NavLink>
<NavLink to="/news">News</NavLink>
<Theme />
</nav>
);
}
Example #17
Source File: MenuPanel.js From tulip-frontend with GNU Affero General Public License v3.0 | 5 votes |
function MenuItem({
to,
externalLink = false,
icon,
iconActive,
label,
onActivate,
}) {
const history = useHistory()
const active = useRouteMatch(to) !== null
const theme = useTheme()
const handlePageRequest = useCallback(() => {
onActivate()
!externalLink ? history.push(to) : window.location.assign(to)
}, [history, onActivate, to, externalLink])
return (
<ButtonBase
onClick={handlePageRequest}
css={`
display: flex;
align-items: center;
margin-top: ${GU * 2}px;
width: 100%;
height: ${5 * GU}px;
padding: 0 ${2 * GU}px 0 ${3 * GU}px;
border-radius: 0;
text-align: left;
background: 'transparent';
`}
>
<div
css={`
position: absolute;
left: 0;
width: 3px;
height: 100%;
opacity: ${Number(active)};
transform: translate3d(${active ? '0%' : '-100%'}, 0, 0);
transform-position: 0 0;
transition-property: transform, opacity;
transition-duration: 150ms;
transition-timing-function: ease-in-out;
`}
/>
<img src={active ? iconActive : icon} alt="" />
<span
css={`
margin-left: ${2 * GU}px;
overflow: hidden;
text-overflow: ellipsis;
${textStyle('body2')};
color: ${active ? '#2C3437' : theme.contentSecondary};
font-weight: ${active ? '700' : '300'};
`}
>
{label}
</span>
</ButtonBase>
)
}
Example #18
Source File: AppContainer.js From akashlytics-deploy with GNU General Public License v3.0 | 5 votes |
AppContainer = () => {
const classes = useStyles();
const [isAppInitiated, setIsAppInitiated] = useState(false);
const { address, selectedWallet } = useWallet();
const { wallets } = useStorageWallets();
const [showBetaBanner, setShowBetaBanner] = useState(false);
const history = useHistory();
const walletsExist = wallets.length > 0;
useEffect(() => {
// Redirect to wallet import or open when no current selected wallet
if (!selectedWallet || !address) {
if (walletsExist) {
history.replace(UrlService.walletOpen());
} else {
history.replace(UrlService.register());
}
}
let isBetaBannerSeen = localStorage.getItem("isBetaBannerSeen");
isBetaBannerSeen = !!isBetaBannerSeen && isBetaBannerSeen === "true" ? true : false;
setShowBetaBanner(!isBetaBannerSeen);
setIsAppInitiated(true);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<>
{showBetaBanner && <BetaBanner />}
<NodeStatusBar />
<div className={classes.body}>
<ErrorBoundary FallbackComponent={ErrorFallback}>
<Route exact path="/register">
<Register />
</Route>
<Route exact path="/new-wallet">
<NewWallet />
</Route>
<Route exact path="/wallet-import">
<WalletImport />
</Route>
<Route exact path="/wallet-open">
<WalletOpen />
</Route>
</ErrorBoundary>
{isAppInitiated && selectedWallet && address && <MainView />}
</div>
<Footer />
</>
);
}
Example #19
Source File: Chats.js From Realtime-Chat-Application-ReactJs with MIT License | 5 votes |
Chats = () => {
const history = useHistory();
const { user } = useAuth();
const [loading, setLoading] = useState(true);
const handleLogout = async () => {
await auth.signOut();
history.push("/");
};
const getFile = async (url) => {
const response = await fetch(url);
const data = await response.blob();
return new File([data], "userPhoto.jpg", { type: "image/jpeg" });
};
useEffect(() => {
if (!user) {
history.push("/");
return;
}
axios
.get("https://api.chatengine.io/users/me", {
headers: {
"project-id": process.env.REACT_APP_CHAT_ENGINE_ID,
"user-name": user.email,
"user-secret": user.uid,
},
})
.then(() => {
setLoading(false);
})
.catch(() => {
let formdata = new FormData();
formdata.append("email", user.email);
formdata.append("username", user.email);
formdata.append("secret", user.uid);
getFile(user.photoURL).then((avatar) => {
formdata.append("avatar", avatar, avatar.name);
axios
.post("https://api.chatengine.io/users", formdata, {
headers: { "private-key": process.env.REACT_APP_CHAT_ENGINE_KEY },
})
.then(() => setLoading(false))
.catch((error) => console.log(error));
});
});
}, [user, history]);
if (!user || loading) return "Loading...";
return (
<div className="chats-page">
<div className="nav-bar">
<div className="logo-tab">MyChat</div>
<div onClick={handleLogout} style={{ marginRight: "150px"}} className="logout-tab">
Logout
</div>
</div>
<ChatEngine
height="calc(100vh - 66px)"
projectID={process.env.REACT_APP_CHAT_ENGINE_ID}
userName={user.email}
userSecret={user.uid}
/>
</div>
);
}
Example #20
Source File: Friendships.js From tisn.app with GNU Affero General Public License v3.0 | 5 votes |
Friendships = (props) => {
const {
user,
userIsCurrentUser,
pendingFriendships,
handleFriendshipClick,
acceptedFriendships,
} = props;
const { t } = useTranslation();
const history = useHistory();
const style = Style();
const friendshipsPendingCurrentUserAction =
userIsCurrentUser &&
pendingFriendships &&
pendingFriendships.length > 0 &&
pendingFriendships.filter(
(friendship) => friendship.receivant._id === user._id
);
return (
<div className={style.root}>
<Grid container justify="center" spacing={2}>
{friendshipsPendingCurrentUserAction &&
friendshipsPendingCurrentUserAction.length > 0 && (
<Grid item className={style.fullWidth}>
<ExpansionPanel>
<ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}>
{t('friendships.pending')}
</ExpansionPanelSummary>
<ExpansionPanelDetails>
<FriendshipsTable
friendships={friendshipsPendingCurrentUserAction}
displayActions={true}
handleFriendshipClick={handleFriendshipClick}
/>
</ExpansionPanelDetails>
</ExpansionPanel>
</Grid>
)}
{acceptedFriendships && acceptedFriendships.length > 0 ? (
acceptedFriendships.map((friendship) => (
<Grid item key={friendship._id} md={4} sm={6} xs={12}>
<UserCard
user={
friendship.requestant._id === user._id
? friendship.receivant
: friendship.requestant
}
/>
</Grid>
))
) : (
<Grid item>
<div className={`${style.fullWidth} ${style.center}`}>
<Typography gutterBottom={userIsCurrentUser} variant="body1">
{userIsCurrentUser
? t('friendships.haveNoFriendships')
: t('friendships.hasNoFriendships', { name: user.name })}
</Typography>
{userIsCurrentUser && (
<Button
variant="contained"
color="primary"
onClick={() => history.push('/users')}
>
{t('friendships.browse')}
</Button>
)}
</div>
</Grid>
)}
</Grid>
</div>
);
}
Example #21
Source File: FloatingButton.js From viade_en2b with MIT License | 5 votes |
FloatingButton = (props) => {
let history = useHistory();
const [recording,setRecording] = useState(false);
const startRecording = ()=>{
toast.info("Route recording started", {
draggable: true,
position: toast.POSITION.TOP_CENTER
});
setRecording(true);
RealTimeRoute.default.main()
}
const finishRecording = ()=>{
toast.info("Route recording stopped", {
draggable: true,
position: toast.POSITION.TOP_CENTER
});
setRecording(false);
RealTimeRoute.default.stop();
//props.showSaveRoute();
history.push('/saveroute')
}
return (
<Fab className="mainButton"
event={'click'}
icon={<i className ="fa fa-plus fafab"></i>}
>
<Action className="actionButton" text="Add route"><i className="fa fa-map-pin fafab"></i></Action>
<Action className="actionButton" text="Take Photo" onClick={props.showUpload}><i className="fa fa-camera fafab"></i></Action>
{
recording ? <Action className="actionButton" text="Stop" onClick={() => finishRecording()}><i className="fa fas fa-stop"></i></Action>
:<Action className="actionButton" text="Record" onClick={() => startRecording()}><i className="fa fa-circle"></i></Action>
}
</Fab>
);
}
Example #22
Source File: InstructorClasses.js From front-end with MIT License | 5 votes |
InstructorClasses = ()=>{
const [classes, setClasses]= useState([]);
const [signout, setSignout]= useState(false);
const {push}= useHistory();
useEffect(()=>{
axiosWithAuth()
.get("/classes")
.then(res=>{
console.log("data classes: ", res.data);
setClasses(res.data)
})
.catch(err=> console.log("instructorClasses.js error: ", err))
},[])
const signOut = ()=>{
if (signout===false){
return push('/InstructorLogin')
}
else{
return console.log('you are still logged in')
}
}
return(
<div>
<h1>Instructor classes: </h1>
<Link to="/Instructor/CreateClass"> <button>Create Class</button> </Link>
<button>Delete Class</button>\
<button onClick={signOut}>Sign out</button>
{classes.map((item,key)=>(
<div key={item.id}>
<Card style={{ width: '18rem', margin:' 0 auto', background: 'rgba(97, 136, 207, 0.534)'}}>
<Card.Body>
<Card.Title>Name: {item.name }</Card.Title>
<ListGroup> Location: {item.location}</ListGroup>
<ListGroup> Type: {item.type}</ListGroup>
<ListGroup> Intensity Level: {item.intensityLevel}</ListGroup>
<ListGroup> Start Time: {item.startTime}</ListGroup>
<ListGroup> Duration: {item.duration}</ListGroup>
<ListGroup> Max Class Size: {item.maxClassSize}</ListGroup>
<ListGroup> Attendees: {item.attendees}</ListGroup>
<Button>Click for more information</Button>
</Card.Body>
</Card>
</div>
))}
</div>
)
}
Example #23
Source File: Login.js From Encon-fe with MIT License | 5 votes |
Login = () => {
const { handleSubmit, register, errors, reset } = useForm();
const baseUrl = 'https://encon-be.herokuapp.com/api';
// const [loginError, setLoginError] = useState();
const history = useHistory();
const onLoginSubmit = (data) => {
axios
.post(baseUrl + '/auth/login', {
email: data.email,
password: data.password,
})
.then((res) => {
reset();
localStorage.setItem('AUTH_TOKEN', res.data.token);
localStorage.setItem('USER_ID', res.data.Data.id);
localStorage.setItem('USER_NAME', res.data.Data.name);
localStorage.setItem('USER_LOCATION', res.data.Data.state);
history.push('/profile');
})
.catch((err) => {
// setLoginError('Login Error: ' + err.response.data.error.message);
});
};
return (
<div className='login-container'>
<HeaderAlt />
<form className='loginForm' onSubmit={handleSubmit(onLoginSubmit)}>
<label htmlFor='email' className='label'>
Email
</label>
<input
type='email'
name='email'
ref={register({ required: true, pattern: /^\S+@\S+$/i })}
/>
<ErrorMessage error={errors.email} />
{errors.email && errors.email.message}
<label htmlFor='password' className='label'>
Password
</label>
<input
type='password'
name='password'
ref={register({ required: true })}
/>
<ErrorMessage error={errors.password} />
<button className='app-buttons' type='submit' data-testid='sign in'>
Sign In
</button>
{/* <div>{loginError}</div> */}
</form>
</div>
);
}
Example #24
Source File: QuoteError.js From Merch-Dropper-fe with MIT License | 5 votes |
QuoteError = ({ error }) => {
const classes = useStyles();
const history = useHistory();
const thisStore = localStorage.getItem('domain_name')
// getModalStyle is not a pure function, we roll the style only on the first render
const [modalStyle] = useState(getModalStyle);
const [open, setOpen] = useState(false);
useEffect(()=> {
if(error){
setOpen(true)
} else {
setOpen(false)
}
}, [error])
// can be broken out to it's own component and imported if need be
const readError = error => {
let errorMessage;
if(error === "orderToken is null"){
errorMessage = "There was a problem processing the order. Likely there was an issue with your shipping address, please try again. If the problem persists, contact the Merch Dropper development team"
} else {
errorMessage = "Unknown error, please try again. If the problem persists, contact the Merch Dropper development team"
}
return(
<div style={modalStyle} className={classes.paper}>
<h2 id="simple-modal-title">OOF! ?</h2>
<p id="simple-modal-description">
{errorMessage}
</p>
<Button onClick={()=> history.push(`/${thisStore}/shippingAddress`)}>Try Again</Button>
<Button onClick={()=> history.push(`/${thisStore}`)}>Back to Store</Button>
</div>
);
}
const handleOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
const body = readError(error)
return (
<div>
<Modal
open={open}
onClose={handleClose}
aria-labelledby="simple-modal-title"
aria-describedby="simple-modal-description"
>
{body}
</Modal>
</div>
);
}
Example #25
Source File: ProgressHeader.js From allay-fe with MIT License | 5 votes |
ProgressHeader = ({ progress }) => {
//progress bar
const history = useHistory()
return (
<Flex
justify="center"
px="10%"
w="100%"
h="198px"
background="#F2F6FE"
top="0"
position="fixed"
overflow="hidden"
zIndex="999"
direction="column"
>
<Flex w="100%" justify="space-between" pb="3%">
<h2 fontSize="24px" color="#131C4D" fontFamily="poppins">
Write a review
</h2>
<Button
border="none"
backgroundColor="#F2F6FE"
color="#344CD0"
fontSize="1.3em"
rounded="50px"
_hover={{ color: '#3B4DA6', cursor: 'pointer' }}
onClick={() => {
history.push('/dashboard')
}}
>
Cancel
</Button>
</Flex>
<Flex w="100%" justify="space-between" mb="1%">
{progress && progress.prec === 100 ? (
<>
<Flex as="h4" fontFamily="muli" color="#131C4D" w="50%">
{progress && progress.prec}% Completed!
</Flex>
</>
) : (
<>
<Flex as="h4" fontFamily="muli" color="#131C4D" w="50%">
{progress && 100 - progress.prec}% completed
</Flex>
</>
)}
<Flex width="100px" justify="space-evenly" align="flex-end">
<Image src={require('../../../icons/clock.png')} /> {progress.time}{' '}
min
</Flex>
</Flex>
<ProgressBar value={progress && progress.prog} />
</Flex>
)
}
Example #26
Source File: MemberTable.js From foster-together-fe with MIT License | 5 votes |
function Table({ columns, data, props }) {
const { push } = useHistory();
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow
} = useTable(
{
columns,
data
},
useSortBy
);
const firstPageRows = rows.slice(0, 15);
return (
<TableContain>
<TableHtml {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<TableRow {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<TableHeader
{...column.getHeaderProps(column.getSortByToggleProps())}
>
{column.render("Header")}
<span>
{column.isSorted
? column.isSortedDesc
? " ?"
: " ?"
: ""}
</span>
</TableHeader>
))}
</TableRow>
))}
</thead>
<tbody {...getTableBodyProps()}>
{firstPageRows.map(row => {
prepareRow(row);
return (
<TableRow {...row.getRowProps()}>
{row.cells.map(cell => {
return (
<TableData
onClick={() =>
push(
`/${cell.row.original.userType}/${cell.row.original.id}`
)
}
{...cell.getCellProps()}
>
{cell.render("Cell")}
</TableData>
);
})}
</TableRow>
);
})}
</tbody>
</TableHtml>
<br />
</TableContain>
);
}
Example #27
Source File: MenuComponent.js From grants-fe with MIT License | 5 votes |
export default function MenuComponent({
anchorEl,
menuId,
isMenuOpen,
handleMenuClose,
}) {
const history = useHistory();
const dispatch = useDispatch();
return (
<>
<Menu
anchorEl={anchorEl}
anchorOrigin={{ vertical: "top", horizontal: "right" }}
id={menuId}
keepMounted
transformOrigin={{ vertical: "top", horizontal: "right" }}
open={isMenuOpen}
onClose={handleMenuClose}
>
<MenuItem
onClick={() => {
handleMenuClose();
return history.push("/Homepage");
}}
>
Home
</MenuItem>
<MenuItem
onClick={async () => {
await handleMenuClose();
return history.push("/profile");
}}
>
Profile
</MenuItem>
<MenuItem
onClick={() => {
handleMenuClose();
return history.push("/Grants");
}}
>
Grants
</MenuItem>{" "}
<MenuItem
onClick={() => {
dispatch(logout());
}}
>
Log Out
</MenuItem>
</Menu>
</>
);
}
Example #28
Source File: PasswordChangePage.js From neighborhood-chef-fe with MIT License | 5 votes |
function ChangePassword() {
const [passwordData, setPasswordData] = useState({});
const [error, setError] = useState("");
const { push } = useHistory();
const { string } = useParams();
const id = string.split("-")[0];
const hash = string.split("-")[1];
const handleChange = (e) => {
e.preventDefault();
setError("");
setPasswordData({ ...passwordData, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
if (passwordData.password === passwordData.confirmPassword) {
try {
const body = {
hash,
id,
password: passwordData.password,
};
await axios.post(
`${process.env.REACT_APP_BASE_URL}/auth/initialChangePassword`,
body
);
push("/login");
} catch (err) {
setError(
"Password does not meet requirements. Please ensure you have a capital letter and a special character."
);
console.dir(err);
}
} else setError("Passwords do not match.");
};
return (
<form
style={{
textAlign: "center",
display: "flex",
flexDirection: "column",
alignItems: "center",
marginTop: "50px",
}}
onSubmit={handleSubmit}
>
<input
type="password"
name="password"
placeholder=" Enter your new password"
onChange={handleChange}
></input>
<input
type="password"
name="confirmPassword"
placeholder=" Confirm New Password"
onChange={handleChange}
></input>
<button>Change Password</button>
{error && <p style={{ color: "red" }}>{error}</p>}
</form>
);
}
Example #29
Source File: FirstLoginForm.js From schematic-capture-fe with MIT License | 5 votes |
FirstLoginForm = (props) => {
const { register, handleSubmit, errors } = useForm()
const dispatch = useDispatch()
const history = useHistory()
const { firstLogin } = dispatchers
const onSubmit = (data) => {
dispatch(firstLogin(data = {...data, token: props.match.params.userToken }, history))
}
return (
<FormContainer>
<form className="white" onSubmit={handleSubmit(onSubmit)}>
<Signin className="signin">First Time Log-in</Signin>
<FormGroup>
<StyledField
data-password
type="password"
name="newPassword"
id="newPassword"
placeholder="New Password"
aria-label="New Password"
aria-invalid={errors.password ? "true" : "false"}
aria-describedby="error-password-required"
ref={register({ required: true })}
/>
{errors.password && errors.password.type === "required" && (
<FieldError id="error-password-required">
That's an incorrect password. Try again.
</FieldError>
)}
</FormGroup>
<FormGroup>
<label> Select Security Question
<StyledSelect
name="newQuestion"
label="Select Security Question"
ref={register({ required: true })}>
<option value="What was your childhood nickname?">What was your childhood nickname?</option>
<option value=" In what city did you meet your spouse/significant other?"> In what city did you meet your spouse/significant other?</option>
<option value=" What is the name of your favorite childhood friend?"> What is the name of your favorite childhood friend?</option>
<option value="What street did you live on in third grade?">What street did you live on in third grade?</option>
<option value="What is your oldest sibling's middle name?">What is your oldest sibling's middle name?</option>
<option value="In what city or town was your first job?">In what city or town was your first job?</option>
</StyledSelect>
</label>
</FormGroup>
<FormGroup>
<StyledField
// @TODO: Finish Field for security answer:
name="newAnswer"
id="answer"
ref={register({ required: true })}
placeholder="Answer to Security Question"
aria-label="Answer to Security Question"
/>
</FormGroup>
<FormRow>
<FormColumn>
<Button data-button-continue variant="primary" type="submit">
Continue
</Button>
</FormColumn>
<FormColumn style={{ textAlign: "right" }}>
<Link to="/forgotpassword">Forgot password?</Link>
</FormColumn>
</FormRow>
</form>
</FormContainer>
)
}