updated React-App to React as of Spring 2020

This commit is contained in:
Godmar Back 2020-04-30 11:40:47 -04:00
parent cd09eb1954
commit b0f08b3e8a
19 changed files with 11568 additions and 8240 deletions

19134
react-app/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,20 +1,24 @@
{ {
"name": "react-app", "name": "react-app",
"version": "0.1.0", "version": "0.2.0",
"private": true, "private": true,
"dependencies": { "dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"bootstrap": "^4.1.0", "bootstrap": "^4.1.0",
"formik": "^0.11.11", "formik": "2.1.4",
"prop-types": "^15.6.1", "prop-types": "^15.6.1",
"react": "^16.3.2", "react-redux": "7.2.0",
"react-dom": "^16.3.2", "react-router-dom": "5.1.2",
"react-redux": "^5.0.7", "react-script": "^2.0.5",
"react-router-dom": "^4.2.2", "react-scripts": "3.4.1",
"react-scripts": "1.1.4", "reactstrap": "8.4.1",
"reactstrap": "^5.0.0",
"redux": "^4.0.0", "redux": "^4.0.0",
"redux-thunk": "^2.2.0", "redux-thunk": "^2.2.0",
"superagent": "^3.8.2", "superagent": "5.2.2",
"toastr": "^2.1.4" "toastr": "^2.1.4"
}, },
"scripts": { "scripts": {
@ -23,5 +27,17 @@
"test": "react-scripts test --env=jsdom", "test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject" "eject": "react-scripts eject"
}, },
"proxy": "http://localhost:9999/" "proxy": "http://localhost:9999/",
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
} }

View File

@ -1,3 +1,6 @@
https://reacttraining.com/react-router/web/guides/redux-integration https://reacttraining.com/react-router/web/guides/redux-integration
Updated Spring 2020 to React 16.13.1 and react-redux 7.2.0

View File

@ -14,6 +14,9 @@ export function login(username, password) {
onSuccess(dispatch, data, getState) { onSuccess(dispatch, data, getState) {
toastr.success(`Success logging in: ${JSON.stringify(data)}`); toastr.success(`Success logging in: ${JSON.stringify(data)}`);
}, },
onError(dispatch, data, getState) {
toastr.success(`Error logging in: ${JSON.stringify(data && data.response && data.response.text)}`);
},
}); });
} }

View File

@ -1,17 +1,14 @@
import React from 'react'; import React, { useEffect } from 'react';
import { Redirect } from 'react-router-dom'; import { Redirect } from 'react-router-dom';
import store from '../store'; import store from '../store';
class Logout extends React.Component { const Logout = () => {
componentWillMount() {
// normally, we would inform the server just in case. // normally, we would inform the server just in case.
document.cookie = "auth_token="; document.cookie = "auth_token=";
useEffect(() => {
store.dispatch({ type: "LOGOUT" }); store.dispatch({ type: "LOGOUT" });
} }, []);
render() {
return (<Redirect to="/" />); return (<Redirect to="/" />);
} };
}
export default Logout; export default Logout;

View File

@ -1,5 +1,4 @@
import React from 'react'; import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { import {
Collapse, Collapse,
Navbar, Navbar,
@ -55,37 +54,19 @@ const DropDowns = (props) => {
/** /**
* Navigation bar component * Navigation bar component
*/ */
class NavBar extends React.Component { const NavBar = (props) => {
static propTypes = { let [isOpen, setOpen] = useState(false);
menus: PropTypes.object,
user: PropTypes.object,
branding: PropTypes.string,
}
constructor(props) { const menus = props.menus
super(props); const user = props.user
const toggle = () => { setOpen(!isOpen); }
this.toggle = this.toggle.bind(this);
this.state = {
isOpen: false
};
}
toggle() {
this.setState({
isOpen: !this.state.isOpen
});
}
render() {
const menus = this.props.menus
const user = this.props.user
return ( return (
<div> <div>
<Navbar color="light" light expand="md"> <Navbar color="light" light expand="md">
<NavbarToggler onClick={this.toggle} /> <NavbarToggler onClick={toggle} />
<NavbarBrand to="/">{this.props.branding}</NavbarBrand> <NavbarBrand to="/">{props.branding}</NavbarBrand>
<Collapse isOpen={this.state.isOpen} navbar> <Collapse isOpen={isOpen} navbar>
<Nav className="mr-auto" navbar> <Nav className="mr-auto" navbar>
{menus.topbar.map((item) => {menus.topbar.map((item) =>
<NavItem key={item.path}> <NavItem key={item.path}>
@ -94,22 +75,22 @@ class NavBar extends React.Component {
</NavLink> </NavLink>
</NavItem> </NavItem>
)} )}
{ menus.leftdropdowns && {menus.leftdropdowns &&
<DropDowns className="mr-auto" dropdowns={menus.leftdropdowns} user={user} /> <DropDowns className="mr-auto" dropdowns={menus.leftdropdowns} user={user} />
} }
</Nav> </Nav>
<Nav className="ml-auto"> <Nav className="ml-auto">
{ menus.rightdropdowns && {menus.rightdropdowns &&
<DropDowns className="ml-auto" dropdowns={menus.rightdropdowns} user={user} /> <DropDowns className="ml-auto" dropdowns={menus.rightdropdowns} user={user} />
} }
{isLoaded(user) ? {isLoaded(user) ?
<NavItem> <NavItem>
<NavLink activeClassName="active" tag={RRNavLink} to={this.props.logoutUrl}>Logout ({user.sub})</NavLink> <NavLink activeClassName="active" tag={RRNavLink} to={props.logoutUrl}>Logout ({user.sub})</NavLink>
</NavItem> </NavItem>
: :
<NavItem> <NavItem>
<NavLink activeClassName="active" tag={RRNavLink} to={this.props.loginUrl}>Login</NavLink> <NavLink activeClassName="active" tag={RRNavLink} to={props.loginUrl}>Login</NavLink>
</NavItem> </NavItem>
} }
</Nav> </Nav>
@ -117,7 +98,6 @@ class NavBar extends React.Component {
</Navbar> </Navbar>
</div> </div>
); );
}
} }
export default NavBar; export default NavBar;

View File

@ -3,13 +3,12 @@ import { Row, Label, Input, Alert, Button, ButtonToolbar, Form, FormGroup } from
import { withFormik } from 'formik'; import { withFormik } from 'formik';
/* /*
* This is a connected form that display username/password. * This is a form that display username/password.
* When the user hits submit, the 'onSubmit' method is called * When the user hits submit, the 'onSubmit' method is called
* in the parent, which receives the username/password the user * in the parent, which receives the username/password the user
* entered. It also performs validation. * entered. It also performs validation.
*/ */
class LoginForm extends React.Component { const LoginForm = (props) => {
render() {
const { const {
handleSubmit, // rest is from HOC handleSubmit, // rest is from HOC
isSubmitting, isSubmitting,
@ -21,7 +20,7 @@ class LoginForm extends React.Component {
// touched, // touched,
values, values,
// valid // valid
} = this.props; } = props;
return ( return (
<Form onSubmit={handleSubmit}> <Form onSubmit={handleSubmit}>
@ -41,10 +40,10 @@ class LoginForm extends React.Component {
/> />
</FormGroup> </FormGroup>
{ this.props.autherror && { props.autherror &&
<FormGroup> <FormGroup>
<Alert bsstyle='danger'> <Alert bsstyle='danger'>
{this.props.autherror.message || 'Login failed'} {props.autherror.message || 'Login failed'}
</Alert> </Alert>
</FormGroup> </FormGroup>
} }
@ -67,16 +66,7 @@ class LoginForm extends React.Component {
</Row> </Row>
</Form> </Form>
); );
} };
}
/*
function mapStateToProps(state) {
return {
autherror: state.auth.error
};
}
*/
export default withFormik({ export default withFormik({
mapPropsToValues: () => ({ username: '', password: '' }), mapPropsToValues: () => ({ username: '', password: '' }),

View File

@ -1,42 +0,0 @@
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import { isLoaded } from '../util/loadingObject';
// From https://github.com/gillisd/react-router-v4-redux-auth
const PrivateRoute = ({component: ComposedComponent, ...rest}) => {
class Authentication extends React.Component {
// redirect if not authenticated; otherwise,
// return the component input into <PrivateRoute />
handleRender(props) {
if (!this.props.authenticated) {
return <Redirect to={{
pathname: '/login',
state: {
from: props.location
}
}}/>
} else {
return <ComposedComponent {...props}/>
}
}
render() {
return (
<Route {...rest} render={this.handleRender.bind(this)}/>
)
}
}
function mapStateToProps(state) {
return {authenticated: isLoaded(state.auth)};
}
const AuthenticationContainer = connect(mapStateToProps)(Authentication)
return <AuthenticationContainer/>
}
export { PrivateRoute };

View File

@ -3,13 +3,13 @@ const publicUrl = process.env.PUBLIC_URL
const menus = { const menus = {
topbar : [ topbar : [
{ path: `${publicUrl}/`, label: "Home" }, { path: `/`, label: "Home" },
], ],
leftdropdowns : [ leftdropdowns : [
{ {
label: "Public", label: "Public",
entries: [ entries: [
{ path: `${publicUrl}/public`, label: "Public Content" } { path: `/public`, label: "Public Content" }
] ]
} }
], ],
@ -18,7 +18,7 @@ const menus = {
label: "Private", label: "Private",
onlyifauthenticated: true, onlyifauthenticated: true,
entries: [ entries: [
{ path: `${publicUrl}/protected`, label: "Private Content" } { path: `/protected`, label: "Private Content" }
] ]
} }
] ]

View File

@ -7,7 +7,6 @@ import PublicPage from '../pages/PublicPage';
import NotFoundPage from '../pages/NotFoundPage'; import NotFoundPage from '../pages/NotFoundPage';
import HomePage from '../pages/HomePage'; import HomePage from '../pages/HomePage';
import PrivatePage from '../pages/PrivatePage'; import PrivatePage from '../pages/PrivatePage';
import { PrivateRoute } from '../components/privateroute';
import { Switch, Route, withRouter } from 'react-router-dom'; import { Switch, Route, withRouter } from 'react-router-dom';
@ -17,30 +16,26 @@ import config from '../config/';
* children in the main part of the page. Its children will * children in the main part of the page. Its children will
* be chosen based on the selected route. * be chosen based on the selected route.
*/ */
class AppContainer extends React.Component { const AppContainer = (props) => (
render() {
return (
<div> <div>
<TopNavBar branding="CS3214 Demo App" <TopNavBar branding="CS3214 Demo App 2020"
menus={config.menus} menus={config.menus}
user={this.props.user} user={props.user}
loginUrl={`${config.publicUrl}/login`} loginUrl={`/login`}
logoutUrl={`${config.publicUrl}/logout`} logoutUrl={`/logout`}
/> />
<div className="container-fluid marketing"> <div className="container-fluid marketing">
<Switch> <Switch>
<Route exact path={`${config.publicUrl}/`} component={HomePage} /> <Route exact path={`/`} component={HomePage} />
<Route path={`${config.publicUrl}/logout`} component={Logout} /> <Route path={`/logout`} component={Logout} />
<Route path={`${config.publicUrl}/login`} component={LoginPage} /> <Route path={`/login`} component={LoginPage} />
<Route path={`${config.publicUrl}/public`} component={PublicPage} /> <Route path={`/public`} component={PublicPage} />
<PrivateRoute path={`${config.publicUrl}/protected`} component={PrivatePage} /> <Route path={`/protected`} component={PrivatePage} />
<Route component={NotFoundPage} /> <Route component={NotFoundPage} />
</Switch> </Switch>
</div> </div>
</div> </div>
); );
}
}
function mapStateToProps(state) { function mapStateToProps(state) {
return { return {

View File

@ -0,0 +1,36 @@
/*
* This HOC can be used to wrap components so that if they are rendered without authentication,
* they redirect to '/login' first and then come back.
*/
import React from 'react';
import { Redirect, withRouter } from 'react-router';
import { connect } from 'react-redux';
import { isLoaded } from '../util/loadingObject';
function mapStateToProps(state) {
return {
user: state.auth
};
}
export default function RequireAuthentication(Component) {
const wrapper = props => {
if (isLoaded(props.user)) {
return <Component {...props} />;
} else {
return (
<Redirect
to={{
pathname: `/login`,
state: {
from: props.history.location
}
}}
/>
);
}
};
return withRouter(connect(mapStateToProps)(wrapper));
}

View File

@ -13,6 +13,7 @@ import jQuery from 'jquery'; // for toastr;
import AppContainer from './containers/AppContainer'; import AppContainer from './containers/AppContainer';
import store from './store'; import store from './store';
import {checklogin} from './actions/auth'; import {checklogin} from './actions/auth';
import config from './config';
toastr.options.closeButton = true; toastr.options.closeButton = true;
toastr.options.positionClass = 'toast-bottom-right'; toastr.options.positionClass = 'toast-bottom-right';
@ -23,7 +24,7 @@ store.dispatch(checklogin());
const mountPoint = document.getElementById('root'); const mountPoint = document.getElementById('root');
const rootNode = ( const rootNode = (
<Provider store={store}> <Provider store={store}>
<Router> <Router basename={config.publicUrl}>
<AppContainer /> <AppContainer />
</Router> </Router>
</Provider> </Provider>

View File

@ -1,12 +1,9 @@
import React from 'react'; import React from 'react';
import { Container, Row, Col } from 'reactstrap'; import { Container, Row, Col } from 'reactstrap';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import config from '../config/';
import logo from './logo.svg'; import logo from './logo.svg';
class HomePage extends React.Component { let HomePage = (props) => (
render() {
return (
<Container> <Container>
<h1>CS3214 Demo App</h1> <h1>CS3214 Demo App</h1>
<img alt="" src={logo} className="app-logo" /> <img alt="" src={logo} className="app-logo" />
@ -21,12 +18,10 @@ class HomePage extends React.Component {
</Row> </Row>
<Row> <Row>
<Col> <Col>
Click <Link to={`${config.publicUrl}/protected`}>here</Link> to Click <Link to={`/protected`}>here</Link> to
navigate to a protected section of the app. navigate to a protected section of the app.
</Col> </Col>
</Row> </Row>
</Container>); </Container >);
}
}
export default HomePage export default HomePage

View File

@ -1,6 +1,5 @@
import React from 'react'; import React from 'react';
import { connect } from 'react-redux'; import { useDispatch, useSelector } from 'react-redux';
import PropTypes from 'prop-types';
import { Card, CardHeader, CardBody, Container, Row, Col } from 'reactstrap'; import { Card, CardHeader, CardBody, Container, Row, Col } from 'reactstrap';
import { login } from '../actions/auth.js'; import { login } from '../actions/auth.js';
@ -8,23 +7,15 @@ import { isLoading, isLoaded } from '../util/loadingObject'
import LoginForm from '../components/forms/LoginForm'; import LoginForm from '../components/forms/LoginForm';
import { Redirect } from 'react-router-dom'; import { Redirect } from 'react-router-dom';
class LoginPage extends React.Component { const LoginPage = (props) => {
static contextTypes = { let dispatch = useDispatch();
router: PropTypes.object.isRequired function doLogin({username, password}) {
dispatch(login(username, password));
} }
static propTypes = { const user = useSelector(state => state.auth);
user: PropTypes.object.isRequired
}
doLogin({username, password}) {
this.props.dispatch(login(username, password));
}
render() {
const user = this.props.user;
const isAuthenticated = isLoaded(user); const isAuthenticated = isLoaded(user);
const { from } = this.props.location.state || { from: { pathname: "/" } }; const { from } = props.location.state || { from: { pathname: "/" } };
if (isAuthenticated) { if (isAuthenticated) {
return (<Redirect to={from} />); return (<Redirect to={from} />);
} }
@ -39,21 +30,12 @@ class LoginPage extends React.Component {
<LoginForm <LoginForm
loading={isLoading(user)} loading={isLoading(user)}
autherror={user.error} autherror={user.error}
onSubmit={v => this.doLogin(v)} /> onSubmit={v => doLogin(v)} />
</CardBody> </CardBody>
</Card> </Card>
</Col> </Col>
</Row> </Row>
</Container> </Container>);
);
}
} }
function mapStateToProps(state) { export default LoginPage;
return {
user: state.auth
};
}
export default connect(mapStateToProps)(LoginPage);

View File

@ -4,12 +4,12 @@ import React from 'react';
* See https://facebook.github.io/react/docs/reusable-components.html#stateless-functions * See https://facebook.github.io/react/docs/reusable-components.html#stateless-functions
*/ */
const NotFound = (props) => const NotFound = (props) =>
<div><h1>Route not found Error</h1> (<div><h1>Route not found Error</h1>
<div> <div>
Something went wrong: {window.location.pathname} could not be found! Something went wrong: {window.location.pathname} could not be found!
</div> </div>
{/* JSON.stringify(props) */} {/* JSON.stringify(props) */}
</div> </div>);
export default NotFound export default NotFound

View File

@ -1,13 +1,17 @@
import React from 'react'; import React from 'react';
import { useSelector } from 'react-redux';
import { Container } from 'reactstrap'; import { Container } from 'reactstrap';
import RequireAuthentication from '../containers/RequireAuthentication';
class PrivatePage extends React.Component { const PrivatePage = () => {
render() { let user = useSelector(state => state.auth);
return (
<Container> return (<Container>
<h1>Welcome to a private page</h1> <h1>Welcome to a private page</h1>
<div> <div>
You have successfully authenticated. You have successfully authenticated as user <tt>{user.sub}</tt>.
Your token was issued at {new Date(user.iat*1000).toString()},
it expires {new Date(user.exp*1000).toString()}
</div> </div>
<div> <div>
This page is "private" only inasmuch as the front-end does not This page is "private" only inasmuch as the front-end does not
@ -15,7 +19,6 @@ class PrivatePage extends React.Component {
this page would now perform API requests that require authentication. this page would now perform API requests that require authentication.
</div> </div>
</Container>); </Container>);
}
} }
export default PrivatePage export default RequireAuthentication(PrivatePage);

View File

@ -1,16 +1,12 @@
import React from 'react'; import React from 'react';
import { Container } from 'reactstrap'; import { Container } from 'reactstrap';
class PublicPage extends React.Component { const PublicPage = () => (
render() {
return (
<Container> <Container>
<h1>Welcome to a public page</h1> <h1>Welcome to a public page</h1>
<div> <div>
This public page is accessible to anyone. This public page is accessible to anyone.
</div> </div>
</Container>); </Container>);
}
}
export default PublicPage export default PublicPage;

View File

@ -20,7 +20,7 @@ const checkloginHandler = asyncHandler('CHECKLOGIN', initialState);
export default function(state = initialState, action) { export default function(state = initialState, action) {
let newState; let newState;
if (action.type === 'LOGIN:OK') { if (action.type.startsWith('LOGIN:')) {
newState = loginHandler(state, action); newState = loginHandler(state, action);
} }
if (action.type === 'CHECKLOGIN:OK') { if (action.type === 'CHECKLOGIN:OK') {

View File

@ -3,9 +3,10 @@ import thunk from 'redux-thunk';
import rootReducer from './reducers/root'; import rootReducer from './reducers/root';
const createStoreWithMiddleware = compose( // https://github.com/zalmoxisus/redux-devtools-extension#12-advanced-store-setup
applyMiddleware(thunk), const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
window.devToolsExtension ? window.devToolsExtension() : f => f const createStoreWithMiddleware = composeEnhancers(
applyMiddleware(thunk)
)(createStore); )(createStore);
const store = createStoreWithMiddleware(rootReducer); const store = createStoreWithMiddleware(rootReducer);