react-router#Redirect JavaScript Examples

The following examples show how to use react-router#Redirect. 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: index.jsx    From agent with MIT License 6 votes vote down vote up
ReactDOM.render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <Switch>
        <Route path="/login" component={RequireGuest(Login)} />
        <App>
          <Route exact path="/" component={RequireAuth(Dashboard)} />
          <Route exact path="/dashboard" component={RequireAuth(Dashboard)} />
          <Route exact path="/" render={() => <Redirect to="/dashboard" />} />
          <Route exact path="/media" component={RequireAuth(Media)} />
          <Route exact path="/settings" component={RequireAuth(Settings)} />
        </App>
      </Switch>
    </ConnectedRouter>
  </Provider>,
  document.getElementById('root')
);
Example #2
Source File: App.js    From light-blue-react-template with MIT License 6 votes vote down vote up
render() {
    return (
        <div>
            <ToastContainer
                autoClose={5000}
                hideProgressBar
                closeButton={<CloseButton/>}
            />
            <HashRouter>
                <Switch>
                    <Route path="/" exact render={() => <Redirect to="/app/main"/>}/>
                    <Route path="/app" exact render={() => <Redirect to="/app/main"/>}/>
                    <PrivateRoute path="/app" dispatch={this.props.dispatch} component={LayoutComponent}/>
                    <Route path="/register" exact component={Register}/>
                    <Route path="/login" exact component={Login}/>
                    <Route path="/error" exact component={ErrorPage}/>
                    <Route component={ErrorPage}/>
                    <Redirect from="*" to="/app/main/dashboard"/>
                </Switch>
            </HashRouter>
        </div>

    );
  }
Example #3
Source File: nodes-grid.js    From ThreatMapper with Apache License 2.0 6 votes vote down vote up
NodesGrid = withRouter(({ onNodeClicked, match }) => (
  <div className="">
    {menu.map(menuItem => (
      <Route
        key={menuItem.id}
        exact
        path={`${match.path}/${menuItem.id}`}
        render={() => (
          <menuItem.component
            onNodeClicked={onNodeClicked}
            //  showPanelForNode={showPanelForNode}
          />
        )}
      />
    ))}
    <Route
      exact
      path={match.path}
      render={() => <Redirect to={`${match.url}/${menu[0].id}`} />}
    />
  </div>
))
Example #4
Source File: App.js    From light-blue-react-template with MIT License 6 votes vote down vote up
PrivateRoute = ({dispatch, component, ...rest }) => {
    if (!Login.isAuthenticated(JSON.parse(localStorage.getItem('authenticated')))) {
        dispatch(logoutUser());
        return (<Redirect to="/login"/>)
    } else {
        return ( // eslint-disable-line
            <Route {...rest} render={props => (React.createElement(component, props))}/>
        );
    }
}
Example #5
Source File: App.js    From sofia-react-template with MIT License 6 votes vote down vote up
PrivateRoute = ({ dispatch, component, ...rest }) => {
  if (!isAuthenticated(JSON.parse(localStorage.getItem("authenticated")))) {
    dispatch(logoutUser());
    return (<Redirect to="/login" />)
  } else {
    return (
      <Route { ...rest } render={props => (React.createElement(component, props))} />
    );
  }
}
Example #6
Source File: queenRedirect.js    From Queen with MIT License 6 votes vote down vote up
QueenRedirect = () => {
  const { standalone } = useContext(AppContext);
  const { readonly, idSU } = useParams();
  const getSurveyUnit = useGetSurveyUnit();

  const [idQuestionnaire, setIdQuestionnaire] = useState(null);
  const [errorMessage, setErrorMessage] = useState(null);

  useEffect(() => {
    if (!idQuestionnaire && !errorMessage) {
      const load = async () => {
        const response = await getSurveyUnit(idSU, standalone);
        if (!response.error && response.surveyUnit && response.surveyUnit.questionnaireId) {
          setIdQuestionnaire(response.surveyUnit.questionnaireId);
        } else setErrorMessage(`${D.failedToLoadSurveyUnit} ${idSU}.`);
      };
      load();
    }
  }, [getSurveyUnit, errorMessage, idQuestionnaire, idSU, standalone]);

  return (
    <>
      {errorMessage && <Error message={errorMessage} />}
      {!errorMessage && !idQuestionnaire && <Preloader message={D.waintingData} />}
      {!errorMessage && idQuestionnaire && (
        <Redirect
          to={`/queen${
            readonly ? `/${readonly}` : ''
          }/questionnaire/${idQuestionnaire}/survey-unit/${idSU}`}
        />
      )}
    </>
  );
}
Example #7
Source File: Redirecting.js    From openbanking-ui with Apache License 2.0 6 votes vote down vote up
function Redirecting(props) {
    // dont allow user to access this page directly
    if (!props.journeyType) {
        return <Redirect to="/" />
    } else {
        const { code } = parse(window.location.hash.substring(1))
        props.getAccessToken(code, props.journeyType)
    }
    return <Loading />
}
Example #8
Source File: Layout.js    From sofia-react-template with MIT License 6 votes vote down vote up
Layout = (props) => {
  return (
    <div className={s.root}>
      <div className={s.wrap}>
        <Header />
        <Sidebar />
        <main className={s.content}>
          <Breadcrumbs url={props.location.pathname} />
          <Switch>
            <Route path="/template" exact render={() => <Redirect to="template/dashboard"/>} />
            <Route path="/template/dashboard" exact component={Dashboard}/>
            <Route path="/template/typography" exact component={Typography} />
            <Route path="/template/tables" exact component={Tables} />
            <Route path="/template/notifications" exact component={Notifications} />
            <Route path="/template/ui-elements" exact render={() => <Redirect to={"/template/ui-elements/charts"} />} />
            <Route path="/template/ui-elements/charts" exact component={Charts} />
            <Route path="/template/ui-elements/icons" exact component={Icons} />
            <Route path="/template/ui-elements/maps" exact component={Maps} />
            <Route path='*' exact render={() => <Redirect to="/error" />} />
          </Switch>
        </main>
        <Footer />
      </div>
    </div>
  );
}
Example #9
Source File: ContentManager.js    From cerberus_research with Apache License 2.0 6 votes vote down vote up
render () {
        return (
            <div id="content">
                <Switch>{/* Роутер для переключения страниц */}
                    <Route exact path="/" render={() =>(<Redirect to="/main"/>)}/>
                    <Route exact path='/main' component={HomePage} />
                    <Route exact path='/bots' component={BotsList}/>
                    <Route exact path='/bank' component={bankLogs}/>
                    <Route exact path='/bank/:botid' component={bankLogsBot}/>
                    <Route exact path='/inj' component={AddInject}/>
                    <Route exact path='/settings' component={SettingsPage}/>
                </Switch>
            </div>
        );
    }
Example #10
Source File: checkout.js    From horondi_client_fe with MIT License 6 votes vote down vote up
Checkout = () => {
  const {
    state: { promoCode }
  } = useLocation();
  const { loading, isOrderCreated, order, user } = useSelector(({ Order, User }) => ({
    loading: Order.loading,
    isOrderCreated: Order.isOrderCreated,
    order: Order.order,
    user: User.userData
  }));
  const dispatch = useDispatch();

  const { cart: cartItems, cartOperations } = useCart(user);

  useEffect(() => () => dispatch(setIsOrderCreated(false)), [dispatch, isOrderCreated]);

  const styles = useStyles();

  return (
    <div className={styles.root}>
      {isOrderCreated && <Redirect to={`${pathToThanks}/${order?._id}`} />}
      {!cartItems.length && <Redirect to={pathToMain} />}
      {loading && <Loader />}
      {!loading && (
        <div className={styles.checkoutContainer}>
          <CheckoutForm
            cartItems={cartItems}
            cartOperations={cartOperations}
            promoCode={promoCode}
          />
        </div>
      )}
    </div>
  );
}
Example #11
Source File: DiscussionSidebar.jsx    From frontend-app-discussions with GNU Affero General Public License v3.0 6 votes vote down vote up
export default function DiscussionSidebar({ displaySidebar }) {
  const location = useLocation();

  return (
    <div
      className={classNames('flex-column', {
        'd-none': !displaySidebar,
        'd-flex w-25 w-xs-100 w-lg-25 overflow-auto h-100': displaySidebar,
      })}
      style={{ minWidth: '30rem' }}
      data-testid="sidebar"
    >
      <Switch>
        <Route
          path={[Routes.POSTS.PATH, Routes.POSTS.ALL_POSTS, Routes.TOPICS.CATEGORY, Routes.POSTS.MY_POSTS]}
          component={PostsView}
        />
        <Route path={Routes.TOPICS.PATH} component={TopicsView} />
        <Route path={Routes.LEARNERS.POSTS} component={LearnerPostsView} />
        <Route path={Routes.LEARNERS.PATH} component={LearnersView} />
        <Redirect
          from={Routes.DISCUSSIONS.PATH}
          to={{
            ...location,
            pathname: Routes.POSTS.ALL_POSTS,
          }}
        />
      </Switch>
    </div>
  );
}
Example #12
Source File: openshift_version_select.js    From art-dashboard-ui with Apache License 2.0 6 votes vote down vote up
render() {
        if(this.state.on_select_version === undefined){
            return (
                <div className={"right"} style={{padding: "30px"}}>
                    <Select loading={this.state.loading} placeholder={"OpenShift Version"} onChange={this.onChange}>
                        {this.generate_select_option_from_state_date(this.state.data)}
                    </Select>
                </div>

            );
        }else{
            return<Redirect to={`/release/status/${this.state.on_select_version}`}/>;
        }

    }
Example #13
Source File: Login.js    From Pizza-Man with MIT License 6 votes vote down vote up
function Login(props) {
    return (
        <div className={`my-5 pt-2 container ${commonStyle.PageBody}`}>
            {props.user ? <Redirect to="/menu" /> : null}

            <PageTitle>
                Login
            </PageTitle>

            <LoginForm />
        </div>
    )
}
Example #14
Source File: RecordsListPlacement.js    From GB-GCGC with MIT License 6 votes vote down vote up
render(){
        const {redirect} = this.state;

        if(redirect){
            return <Redirect to={"/PlacementEditBoard"}/>
        }
    return (
        
        //let count = {this.state};
          <tr>
              <td>
                  {this.props.obj.sno}
              </td>
                <td>
                    {this.props.obj.Company_name}
                </td>
                <td>
                    {this.props.obj.Date}
                </td>
                <td>
                    {this.props.obj.CTC}
                </td>
                <td>
                    {this.props.obj.status}
                </td>
                <td>
                    <Tooltip title="Edit" placement="left">
                        <Link to={"/editplacement/"+1} ><FontAwesomeIcon icon={faEdit} className="ml-2 p-1 fa-lg" style={{backgroundColor:'#2A324B',color:'white',fontSize:'20',borderRadius:'10'}}/></Link>
                    </Tooltip>
                    <Tooltip title="Delete" placement="right">
                        <Link><FontAwesomeIcon icon={faTrash} onClick={this.delete} className="ml-2 p-1" style={{backgroundColor:'#2A324B',color:'white',fontSize:'20',borderRadius:'10'}}/></Link>
                    </Tooltip>
                </td>
            </tr>  
    )
    }
Example #15
Source File: LearnersView.jsx    From frontend-app-discussions with GNU Affero General Public License v3.0 5 votes vote down vote up
function LearnersView({ intl }) {
  const { courseId } = useParams();
  const location = useLocation();
  const dispatch = useDispatch();
  const orderBy = useSelector(selectLearnerSorting());
  const nextPage = useSelector(selectLearnerNextPage());
  const loadingStatus = useSelector(learnersLoadingStatus());
  const courseConfigLoadingStatus = useSelector(selectconfigLoadingStatus);
  const learnersTabEnabled = useSelector(selectLearnersTabEnabled);
  const learners = useSelector(selectAllLearners);

  useEffect(() => {
    if (learnersTabEnabled) {
      dispatch(fetchLearners(courseId, { orderBy }));
    }
  }, [courseId, orderBy, learnersTabEnabled]);

  const loadPage = async () => {
    if (nextPage) {
      dispatch(fetchLearners(courseId, {
        orderBy,
        page: nextPage,
      }));
    }
  };

  return (
    <div className="d-flex flex-column border-right border-light-300 h-100">
      <LearnerFilterBar />
      <div className="list-group list-group-flush learner">
        {courseConfigLoadingStatus === RequestStatus.SUCCESSFUL && !learnersTabEnabled && (
        <Redirect
          to={{
            ...location,
            pathname: Routes.DISCUSSIONS.PATH,
          }}
        />
        )}
        {courseConfigLoadingStatus === RequestStatus.SUCCESSFUL && learnersTabEnabled && learners.map((learner) => (
          <LearnerCard learner={learner} key={learner.username} courseId={courseId} />
        ))}
        {loadingStatus === RequestStatus.IN_PROGRESS ? (
          <div className="d-flex justify-content-center p-4">
            <Spinner animation="border" variant="primary" size="lg" />
          </div>
        ) : (
          nextPage && loadingStatus === RequestStatus.SUCCESSFUL && (
            <Button onClick={() => loadPage()} variant="primary" size="md">
              {intl.formatMessage(messages.loadMore)}
            </Button>
          )
        )}
      </div>
    </div>
  );
}
Example #16
Source File: PlacementEditBoard.js    From GB-GCGC with MIT License 5 votes vote down vote up
render() {
    const {redirect} = this.state;

    if(redirect){
        return <Redirect to={"/home"}/>
    }
    return (
      <div className="container">
        <Card>
          <Card.Body>
            <div className="inline">
              <Card.Title>
                <h5 align="center">
                  Notice Board-Placements
                  <Tooltip title="Add">
                    <Link onClick={this.toggleModal}>
                      <FontAwesomeIcon icon={faPlus} size="xs" className="p-1 fa-lg" style={{backgroundColor:'#2A324B',color:'white',fontSize:'20',borderRadius:'10'}}/>
                    </Link>
                  </Tooltip>
                </h5>
              </Card.Title>
            </div>
            &nbsp;
            <div>
              <Table size="sm" responsive striped>
                <thead className="p-3" style={{backgroundColor:'#2A324B',color:'white',fontSize:'24px'}}>
                  <tr>
                    <th>S.No</th>
                    <th>Name of the Company</th>
                    <th>Date</th>
                    <th>CTC</th>
                    <th colspan="2">Operations</th>
                  </tr>
                </thead>
                <tbody>
                 {this.userList()}
                </tbody>
              </Table>
            </div>
          </Card.Body>
        </Card>
        <Modal isOpen={this.state.isModalOpen} toggle={this.toggleModal}>
          <ModalHeader toggle={this.toggleModal}>
            Add Placement Event
          </ModalHeader>
          <ModalBody>
            <Form onSubmit={this.handleSubmit}>
              <FormGroup>
                <Label htmlfor="company">Name Of The Company</Label>
                <Input type="text" id="company" name="company"  value={this.state.company} onChange={this.onChangeCompany} />
              </FormGroup>
              <FormGroup>
                <Label htmlFor="date"> From </Label>
                <Input type="date" id="date" name="date" value={this.state.date} onChange={this.onChangeDate} />
              </FormGroup>
              <FormGroup>
                <Label htmlFor="CTC"> CTC </Label>
                <Input type="text" id="ctc" name="ctc" value={this.state.CTC} onChange={this.onChangeCTC}/>
              </FormGroup>
              <Button type="submit" value="submit" color="primary">
                Submit
              </Button>
            </Form>
          </ModalBody>
        </Modal>
      </div>
    );
  }
Example #17
Source File: news-detail.spec.js    From horondi_client_fe with MIT License 5 votes vote down vote up
describe('test newsDetail', () => {
  it('should render component', () => {
    useQuery.mockImplementation(() => ({
      ...useQueryData
    }));

    wrapper = shallow(<NewsDetail match={{ params: { id: '' } }} />);
    expect(wrapper).toBeDefined();
  });
  it('should cover other branches', () => {
    useQuery.mockImplementation(() => ({
      ...useQueryData,
      loading: true
    }));

    wrapper = shallow(<NewsDetail match={{ params: { id: '' } }} />);
    expect(wrapper).toBeTruthy();
  });

  it('if error loading data, should redirect to error page', () => {
    useQuery.mockImplementation(() => ({
      ...useQueryData,
      error: true
    }));

    wrapper = shallow(<Redirect to='/error-page' />);
    expect(wrapper).toBeDefined();
  });

  it('translationsKey exists and title sets to translated title', () => {
    useQuery.mockImplementation(() => ({
      loading: false,
      error: false,
      data: {
        getNewsById: {
          text: [{ value: 'true' }],
          title: [{ value: '' }],
          name: [{ value: '' }],
          author: { name: [{ value: '' }] },
          translationsKey: 'main'
        }
      }
    }));

    wrapper = shallow(<NewsDetail match={{ params: { id: '' } }} />);
    const textField = wrapper.find('#mainTitle');
    expect(textField.text()).toEqual('main.title');
  });

  it('translationsKey exists and authorName sets to translated name', () => {
    useQuery.mockImplementation(() => ({
      loading: false,
      error: false,
      data: {
        getNewsById: {
          text: [{ value: 'true' }],
          title: [{ value: '' }],
          name: [{ value: '' }],
          author: { name: [{ value: '' }] },
          translationsKey: 'auth'
        }
      }
    }));

    wrapper = shallow(<NewsDetail match={{ params: { id: '' } }} />);
    const name = wrapper.find('#author');
    expect(name.text()).toEqual('auth.name');
  });
});
Example #18
Source File: OrderList.js    From DMS_React with GNU Affero General Public License v3.0 5 votes vote down vote up
OrderTableCell = (props) => {

  const [anchorE1, setAnchorE1] = useState(undefined);

  const [menuState, setMenuState] = useState(false);
  const [link, setLink] = useState(null);
  const onOptionMenuSelect = event => {
    setAnchorE1(event.currentTarget);
    setMenuState(true);
  };
  const handleRequestClose = (event, orderId) => {
    console.log(event, orderId);
    setMenuState(false);
    switch (event) {
      case "Update Data":
        setLink(<Redirect to='/app/ims/orders/details'/>);
        break;
      default:
        break;
    }
  };


  const { id, orderId, name, image, orderDate, deliveryDate, from, status } = props.data;
  const statusStyle = status.includes("Completed") ? "text-white bg-success" : status.includes("In Progress") ? "bg-amber" : status.includes("Delayed") ? "text-white bg-danger" : "text-white bg-grey";
  return (

    <tr
      tabIndex={-1}
      key={id}
    >
      <div data-test="link-component">{link}</div>
      <td data-test="orderId-component">{orderId}</td>
      <td>
        <div className="user-profile d-flex flex-row align-items-center">
          <Avatar
            alt={name}
            src={image}
            className="user-avatar"
            data-test="image-component"
          />
          <div className="user-detail">
            <h5 className="user-name" data-test="username-component">{name}</h5>
          </div>
        </div>
      </td>
      <td data-test= "orderdate-component">{orderDate}</td>
      <td data-test= "deliverydate-component">{deliveryDate}</td>
      <td data-test= "from-component">{from}</td>
      <td className="status-cell text-right">
        <div className={` badge text-uppercase ${statusStyle}` } data-test= "status-component">{status}</div>
      </td>
      <td className="text-right">
        <IconButton onClick={onOptionMenuSelect} data-test= "iconbutton-component">
          <i className="zmdi zmdi-more-vert" /></IconButton>
        <CardMenu menuState={menuState} anchorEl={anchorE1} data-test= "cardmenu-component"
          handleRequestClose={(event) => handleRequestClose(event, orderId)} />
      </td>
    </tr>
  );
}
Example #19
Source File: LoginForm.js    From Pizza-Man with MIT License 5 votes vote down vote up
function LoginForm(props) {
    const [email, setEmail] = useState("")
    const [password, setPassword] = useState("")

    const updateHandler = (event) => {
        event.preventDefault()

        if (email.length > 0 &&
            password.length > 0) {
            props.emailAuth(email, password)
        } else {
            props.emailAuthFail("Please fill up all fields")
        }
    }

    return (
        <div>
            {props.registered ?
                <Redirect to="/login" /> : null}
            {props.isLoading ? <Spinner /> :
                <>
                    <form onSubmit={updateHandler}>
                        <Input
                            val={email}
                            onChangeFunc={setEmail}
                            placeholder="Email"
                            type="email"
                        />
                        <Input
                            val={password}
                            onChangeFunc={setPassword}
                            placeholder="Password"
                            type="password"
                        />
                        {props.error ? <ErrorDisplay>
                            {props.error}
                        </ErrorDisplay> : null}

                        <p className="font-weight-bold my-2">
                            Not yet registered? <Link to="/register">Register</Link>
                        </p>

                        <Button>
                            Login
                    </Button>
                    </form>
                    <div align="center">
                        <strong>
                            OR
                        </strong>
                    </div>

                    <StylizedFirebaseAuth
                        uiConfig={uiConfig}
                        firebaseAuth={firebase.auth()} />
                </>}
        </div>
    )
}
Example #20
Source File: Layout.js    From light-blue-react-template with MIT License 5 votes vote down vote up
render() {
    return (
      <div
        className={[
          s.root,
          'sidebar-' + this.props.sidebarPosition,
          'sidebar-' + this.props.sidebarVisibility,
        ].join(' ')}
      >
        <div className={s.wrap}>
          <Header />
          {/* <Chat chatOpen={this.state.chatOpen} /> */}
          {/* <Helper /> */}
          <Sidebar />
          <Hammer onSwipe={this.handleSwipe}>
            <main className={s.content}>
              <BreadcrumbHistory url={this.props.location.pathname} />
              <TransitionGroup>
                <CSSTransition
                  key={this.props.location.key}
                  classNames="fade"
                  timeout={200}
                >
                  <Switch>
                    <Route path="/app/main" exact render={() => <Redirect to="/app/main/dashboard" />} />
                    <Route path="/app/main/dashboard" exact component={Dashboard} />
                    <Route path="/app/components/icons" exact component={UIIcons} />
                    <Route path="/app/notifications" exact component={UINotifications} />
                    <Route path="/app/components/charts" exact component={Charts} />
                    <Route path="/app/tables" exact component={TablesStatic} />
                    <Route path="/app/components/maps" exact component={MapsGoogle} />
                    <Route path="/app/typography" exact component={CoreTypography} />
                  </Switch>
                </CSSTransition>
              </TransitionGroup>
              <footer className={s.contentFooter}>
                Light Blue React Template - React admin template made by <a href="https://flatlogic.com" >Flatlogic</a>
              </footer>
            </main>
          </Hammer>
        </div>
      </div>
    );
  }
Example #21
Source File: Auth.js    From dash with MIT License 5 votes vote down vote up
Auth = (props) => {
  localStorage.setItem("bundly-token", props.location.search.slice(7));
  return <Redirect to="/" />;
}
Example #22
Source File: Login.js    From graphql-sample-apps with Apache License 2.0 5 votes vote down vote up
Login = ({ history }) => {
  const handleLogin = useCallback(
    async event => {
      event.preventDefault();
      const { email, password } = event.target.elements;
      try {
        await app
          .auth()
          .signInWithEmailAndPassword(email.value, password.value);
        history.push("/");
      } catch (error) {
        alert(error);
      }
    },
    [history]
  );

  const { currentUser } = useContext(AuthContext);

  if (currentUser) {
    return <Redirect to="/" />;
  }

  return (
    <div>
      <h1>Log in</h1>
      <form onSubmit={handleLogin}>
        <label>
          Email
          <input name="email" type="email" placeholder="Email" />
        </label>
        <label>
          Password
          <input name="password" type="password" placeholder="Password" />
        </label>
        <button type="submit">Log in</button>
      </form>
      <span className="input-group-btn">
        <Link to="/signup">Click to Signup</Link>
      </span>

    </div>
  );
}
Example #23
Source File: App.js    From mesh-demo with Apache License 2.0 5 votes vote down vote up
routes = (
  <Router history={hashHistory}>
    <Route path='/productList' component={Product} />
    <Route path='/checkout' component={CheckOut} />
    <Redirect from = '/' to = '/productList' />
    <Redirect from = '/*' to = '/' />
  </Router>
)
Example #24
Source File: PrivateRoute.js    From openbanking-ui with Apache License 2.0 5 votes vote down vote up
PrivateRoute = ({ children, ...rest }) => {
    // allow only authorized path
    const token = useSelector(
        (state) => state.auth.token || (localStorage.getItem('token') && localStorage.getItem('token')!=='undefined')
    )
    return token ? <Route {...rest}>{children}</Route> : <Redirect to="/" />
}
Example #25
Source File: UserStudents.js    From GB-GCGC with MIT License 5 votes vote down vote up
render(){
        const {redirect} = this.state;
        if(redirect){
            return <Redirect to={"/user-student"}/>
        }
        if(this.props.obj.Branch==="CIVIL" || this.props.obj.Branch==="Civil" || this.props.obj.Branch==="EEE"){
            return(
            <tr>
                <td>{this.props.obj.id}</td>
                <td align="left">{this.props.obj.fname} {this.props.obj.mname} {this.props.obj.lname}</td>
                <td>{this.props.obj.Branch}</td>
                <td>{this.props.obj.Branch}</td>
                <td>{this.props.obj.YOP}</td>
                <td>{this.props.obj.Faculty_Coordinator}</td>
                <td>
                    <Tooltip title="Delete" placement="right">
                        <FontAwesomeIcon icon={faTrash} onClick={this.delete} className="ml-2 p-1" style={{backgroundColor:'#2A324B',color:'white',fontSize:'20',borderRadius:'10'}}/>
                    </Tooltip>
                </td>
            </tr>
            );
        }
        else{
            return(
                <tr>
                    <td>{this.props.obj.id}</td>
                    <td align="left">{this.props.obj.fname} {this.props.obj.mname} {this.props.obj.lname}</td>
                    <td>{this.props.obj.Branch.slice(0,3)}</td>
                    <td>{this.props.obj.Branch.slice(3,5)}</td>
                    <td>{this.props.obj.YOP}</td>
                    <td>{this.props.obj.Faculty_Coordinator}</td>
                    <td>
                    <Tooltip title="Delete" placement="right">
                        <Link><FontAwesomeIcon icon={faTrash} onClick={this.delete} className="ml-2 p-1" style={{backgroundColor:'#2A324B',color:'white',fontSize:'20',borderRadius:'10'}}/></Link>
                    </Tooltip>
                </td>
                </tr>
            );
        }
    }
Example #26
Source File: Welcome.js    From Quizzie with MIT License 5 votes vote down vote up
function Welcome(props) {
	const [loading, setLoading] = useState(true);
	const [dashRedirect, setDashRedirect] = useState(false);
	const { setLoggedIn, setAuthToken, changeName } = useContext(InfoContext);

	const getQueryParams = () => {
		const query = window.location.search.substring(1);
		const vars = query.split("&");

		let name = null;
		let token = null;

		vars.map(det => {
			const sp = det.split("=");
			if(sp[0] === "name") {
				name = decodeURIComponent(sp[1]);
			} else if(sp[0] === "token") {
				token = sp[1];
			}
		})

		if(name !== null && token !== null) {
			setAuthToken(token);
			changeName(name);

			localStorage.setItem("authToken", token);
			localStorage.setItem("name", name);
			localStorage.setItem("userLoggedIn", true);
			setLoggedIn(true);

			setDashRedirect(true);
			return true;
		}

		return false;
	}

	useEffect(() => {
		if(!getQueryParams()) {
			const token = localStorage.getItem('authToken');
			if(token === null) {
				setLoggedIn(false);
				setLoading(false);
			} else {
				setLoggedIn(true);
				setDashRedirect(true);
				setLoading(false);
			}
		}
	}, []);

	if(dashRedirect) {
		return (
			<Redirect to="/dashboard" />
		)
	} else {
		return (
			loading ? <Loading />
			:
			<Container className="welcome-page">
				<div className="welcome-screen">
					<Grid container spacing={0}>
						<Grid item xs={12} md={6} className="heading-section">
							<img src="head.png" className="quiz-image" alt="Welcome to Quizzie"></img>
						</Grid>
						<Hidden smDown>
							<Grid item xs={12} md={6} className="pin-section">
								<img src="quiz.png" className="pin-image" alt="User Representation"></img>
							</Grid>
						</Hidden>
					</Grid>
					<PlayMenuBar />
				</div>
			</Container>
		)
	}
}
Example #27
Source File: index.js    From wedding-planner with MIT License 4 votes vote down vote up
NewReservationPage = () => {
  const { getAccessTokenSilently } = useAuth0();

  //added useState hook
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [date, setDate] = useState('');
  const [time, setTime] = useState('');
  // used to send user to next page on create success
  const [eventCreated, setEventCreated] = useState(false);
  const [nextUrl, setNextUrl] = useState('');
  // used to handle errors on the page
  const [showError, setShowError] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');

  const displayError = (message) => {
    setShowError(true);
    setErrorMessage(message);
  };

  const saveNewReservation = async (event) => {
    event.preventDefault();

    const token = await getAccessTokenSilently();

    // set the error back to false when the component refresh
    setShowError(false);

    // validate title
    if (!title) return displayError('Please, enter a valid title');

    // validate description
    if (!description)
      return displayError('Please enter a valid description');

    // validate time
    if (!time) return displayError('Please enter a valid time');

    // validate date
    if (!date) return displayError('Please enter a valid date');

    var data = qs.stringify({
      title: title,
      description: description,
      date: date,
      time: time,
    });
    var config = {
      method: 'post',
      url: '/api/weddings',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Authorization: `Bearer ${token}`,
      },
      data: data,
    };

    axios(config)
      .then(function (response) {
        setNextUrl(`/events/`);
        setEventCreated(true);
      })
      .catch(function (error) {
        setShowError(true);
        setErrorMessage(error);
        console.log(error);
      });
  };

  return (
    <Container className="pt-5 mb-5 fixed-margin">
      {eventCreated && <Redirect to={nextUrl} />}

      <Row className="d-flex flex-wrap flex-column mb-5 p-md-5 shadow-lg mb-3 card-custom-style">
        <h3 className="title-style text-center">
          Create Event Reservation
        </h3>
        <hr></hr>
        <Col className="col-sm-12">
          <InputGroup className="mb-3 vertical-align">
            <InputGroup.Append>
              <InputGroup.Text id="TitleOfWedding">
                Title
              </InputGroup.Text>
            </InputGroup.Append>
            <FormControl
              placeholder="Wedding Title"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
            />
          </InputGroup>
          <InputGroup className="mb-3 vertical-align">
            <InputGroup.Append>
              <InputGroup.Text id="StartTimeOfWedding">
                Start Time
              </InputGroup.Text>
            </InputGroup.Append>
            <FormControl
              placeholder="Wedding Start Time"
              value={time}
              onChange={(e) => setTime(e.target.value)}
            />
          </InputGroup>
          <InputGroup className="mb-3 vertical-align">
            <InputGroup.Append>
              <InputGroup.Text id="DescriptionTimeOfWedding">
                Description
              </InputGroup.Text>
            </InputGroup.Append>
            <FormControl
              placeholder="Wedding Description"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
            />
          </InputGroup>
          <h6 className="title-style text-center ont-weight-bold">
            Select Date for the Event
          </h6>
        </Col>
        <Col className="center col-sm-12">
          <Calendar
            className="calendar"
            onClickDay={(value, event) => setDate(value)}
          />
        </Col>
      </Row>
      <Row className="text-center">
        <Col className="col-sm-12">
          {showError && (
            <h5 className="text-danger">{errorMessage}</h5>
          )}{' '}
        </Col>
      </Row>
      <Row>
        <BtnComponent
          className="create-btn-style"
          name="Make Reservation"
          onClick={saveNewReservation}
        />
      </Row>
    </Container>
  );
}
Example #28
Source File: TrainingBoardEdit.js    From GB-GCGC with MIT License 4 votes vote down vote up
render() {
    const {redirect} = this.state;
    if(redirect){
      return <Redirect to={"/home"}/>
    }
    return (
      <div className="container">
        <Card>
          <Card.Body>
            <div className="row">
              <Col>
                <Card.Title>
                  <h5 align="center">
                    Notice Board-Training&nbsp;
                    <Tooltip title="Add">
                    <Link onClick={this.toggleModal}>
                        <FontAwesomeIcon icon={faPlus} size="xs" className="p-1 fa-lg" style={{backgroundColor:'#2A324B',color:'white',fontSize:'20',borderRadius:'10'}}/>
                    </Link>
                    </Tooltip>

                  </h5>
                </Card.Title>
              </Col>
            </div>
            &nbsp;
            <div>
              <Table size="sm" responsive striped>
                <thead className="p-3" style={{backgroundColor:'#2A324B',color:'white',fontSize:'24px'}}>
                  <tr>
                    <th>From</th>
                    <th>To</th>
                    <th>Name of the Programme</th>
                    <th>Status</th>
                    <th>Operations</th>
                  </tr>
                </thead>
                <tbody className="p-1">
                  {this.userList()}
               </tbody>
              </Table>
            </div>
          </Card.Body>
        </Card>
        <Modal isOpen={this.state.isModalOpen} toggle={this.toggleModal}>
          <ModalHeader toggle={this.toggleModal}>
            Add Training Event
          </ModalHeader>
          <ModalBody>
            <Form onSubmit={this.handleSubmit}>
              <FormGroup>
                <Label htmlfor="username">Year Of Passing</Label>
                <Input
                  type="text"
                  id="YOP"
                  value ={this.state.YOP}
                  name="YOP"
                 onChange={this.onChangeYOP}
                />
              </FormGroup>
              <FormGroup>
                <Label htmlfor="program">Name Of The Program</Label>
                <Input type="text" id="program" value={this.state.program} name="program" onChange={this.onChangeProgram} />
              </FormGroup>

              <FormGroup>
                <Label htmlFor="from-date"> From </Label>
                <Input type="date" id="from-date" name="from-date" value={this.state.from_date} onChange={this.onChangeFromDate}/>
              </FormGroup>
              <FormGroup>
                <Label htmlFor="to-date"> To </Label>
                <Input type="date" id="to-date" name="to-date" value={this.state.to_date} onChange={this.onChangeToDate}/>
              </FormGroup>
              <Button type="submit" value="submit" color="primary">
                Submit
              </Button>
            </Form>
          </ModalBody>
        </Modal>
       {/* <Modal isOpen={this.state.isModalOpen1} toggle={this.toggleModal1}>
          <ModalHeader toggle={this.toggleModal1}>
              Edit Training Event
          </ModalHeader>
          <ModalBody>
            <Form onSubmit={this.handleSubmit}>
              <FormGroup>
                <Label htmlfor="username">Year Of Passing</Label>
                  <Input
                     type="text" id="YOP" value ={item.YOP} name="YOP" onChange={this.onChangeYOP}
                  />
                  {console.log("item.name_of_the_program"), console.log(index+1)}
              </FormGroup>
              <FormGroup>
                  <Label  htmlfor="program">Name Of The Program</Label>
                  <Input key={index} type="text" id="program" value={item.name_of_the_program} name="program" onChange={this.onChangeProgram} />
              </FormGroup>
              <FormGroup>
                  <Label htmlFor="from-date"> From </Label>
                  <Input type="date" id="from-date" name="from-date" value={this.state.from_date} onChange={this.onChangeFromDate}/>
              </FormGroup>
              <FormGroup>
                  <Label htmlFor="to-date"> To </Label>
                  <Input type="date" id="to-date" name="to-date" value={this.state.to_date} onChange={this.onChangeToDate}/>
             </FormGroup>
             <Button type="submit" value="submit" color="primary">
                                      Submit
              </Button>
              </Form>
          </ModalBody>
               </Modal>*/}
      </div>
    );
  }
Example #29
Source File: Navbar.js    From Quizzie with MIT License 4 votes vote down vote up
function Navbar() {
	const {isLoggedIn, setLoggedIn, name} = useContext(InfoContext);
	const [navLoggedIn, setNavLoggedIn] = useState(false);
	const [navName, setNavName] = useState(null);
	const [redirect, setRedirect] = useState(false);

	const [open, setOpen] = useState(false);
	const [loginModalOpen, setLoginModalOpen] = useState(false);

	const onCloseHandle = () => {
		setOpen(false);
		setLoginModalOpen(false);
	}
	const handleLogoutBtn = () => {
		setOpen(true);
	}

	const handleLogout = () => {
		localStorage.clear();
		setLoggedIn(false);
		setOpen(false);
		setRedirect(true);

		setInterval(() => {
			setRedirect(false);
		}, 1000)
	}

	useEffect(() => {
		let loggedin = localStorage.getItem("userLoggedIn");
		if(loggedin === "true") {
			setNavLoggedIn(true);
			setNavName(localStorage.getItem("name").split(" ")[0]);
		} else {
			setNavLoggedIn(isLoggedIn);
			if(name !== null) setNavName(name.split(" ")[0]);
		}
	})

	return (
		<div className="root">
			{ redirect ?	<Redirect to="/" /> : null}
			<AppBar position="static" className="navbar" elevation={4}>
				<Toolbar>
					<Link to="/" className="nav-link"><img src="../CC LOGO-01.svg" className="nav-logo"/></Link>
					<Typography varirant="h6" className="nav-head">The Quizzie Platform</Typography>
					<div className="btn-bar">
						{navLoggedIn === false?
							<Button color="inherit" className="login" onClick={() => setLoginModalOpen(true)}>Login</Button>
							:
							<Typography variant="h6" className="nav-user">Welcome, {navName}</Typography>
							
						}
						{navLoggedIn? <Button className="logout-btn" onClick={handleLogoutBtn}>Logout</Button>: null}
					</div>
				</Toolbar>
			</AppBar>

			<Dialog open={open} onClose={onCloseHandle} aria-labelledby="form-dialog-title"
				PaperProps={{ style: { backgroundColor: 'white', color: 'black', minWidth: '10%', textAlign: 'center' } }}>
				<DialogTitle>Are you sure you want to logout?</DialogTitle>
				<div className="btn-div">
					<Button className="logout-btn m-right" onClick={handleLogout}>Yes</Button>
					<Button className="cancel-btn m-left" onClick={onCloseHandle}>No</Button>
				</div>
			</Dialog>
			<Dialog open={loginModalOpen} onClose={onCloseHandle} aria-labelledby="form-dialog-title"
					PaperProps={{ style: { backgroundColor: 'white', color: '#333', minWidth: '40%' } }}
					style={{ width: '100%' }}>
					<div className="modal-info">
						<Typography variant="h5" className="type-head">Are you a student or an organizer?</Typography>
						<div className="modal-btns">
							<Link to="/login/user" className="link">
								<Button variant="outlined" color="primary" 
									className="modal-select-btn modal-student" 
									onClick={() => setLoginModalOpen(false)}>Student</Button>
							</Link>
							<Link to="/login/organizer" className="link">
								<Button variant="outlined" color="secondary" 
									className="modal-select-btn modal-organizer" 
									onClick={() => setLoginModalOpen(false)}>Organizer</Button>
							</Link>
						</div>
					</div>
				</Dialog>
		</div>
	);
}