Friday

React.js: dynamic sidebar example with typescript

I'm trying to implement a generic sidebar in my react project.
* I used prime react sidebar.
* It can be used multiple times in the page/application
* It loads different prime react buttons for every sidebar.
* For every sidebar its own onclick function is called when buttons has clicked.

Example screenshots:























project structure:




















index.tsx
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { createStore, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import App from './components/app';
import reducer from './reducer/reducer';

const rootReducer = combineReducers(
  { reducer: reducer}
 );
const store = createStore(rootReducer);

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);
app.tsx
import React from 'react';
import { connect } from 'react-redux';
import { BrowserRouter as Router } from 'react-router-dom';
import Home from './home/home';
import { SET_USER } from '../static/reducerActionTypes';

interface IDispatchProps {
    setUser: (user: string) => void;
}

type IProp = IDispatchProps;

class App extends React.PureComponent<IProp> {
    constructor(props: IProp) {
        super(props);
    }

    componentDidMount() {
        const { setUser } = this.props;
        setUser('Eda Merdan Biricik');
    }

    componentWillUnmount() {
        const { setUser } = this.props;
        setUser('');
    }

    render() {
        return (
            <Router>
                <div className="app">
                    <Home />
                </div>
            </Router>
        );
    }
}

const mapDispatchToProps = (dispatch: any) => ({
    setUser: (user: string) => {
        dispatch({
            user,
            type: SET_USER,
        });
    },
});

export default connect(null, mapDispatchToProps)(App);
home.tsx
import React from 'react';
import MyLeftSidebar from "../sidebar/myLeftSidebar";
import MyRightSidebar from "../sidebar/myRightSidebar";

export default () => (
    <>
        <div>
            <MyLeftSidebar />
        </div>
        <div>
             <MyRightSidebar />
        </div>
    </>
);
myLeftSidebar.tsx
import React from 'react';
import { connect } from 'react-redux';
import CommonSidebar from '../../commons/sidebar/commonSidebar';

const sidebarParameters = {
    fetchApiParameter: 'left',
    reducerKey: 'leftSidebarButtons',
    position: 'left',
};

interface IStateProps {
    user: string;
}

type IProp = IStateProps;

class MyLeftSidebar extends React.PureComponent<IProp> {
    constructor(props: IProp) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick(params: any) {
        alert('do want you want. my params: ' + params);
    }

    render() {
        const { user } = this.props;

        return (
            <>
                {user !== null &&
                <CommonSidebar
                    handleOnClick={this.handleClick}
                    sidebarParameters={sidebarParameters}
                />
                }
            </>
        );
    }
}

const mapStateToProps = ({ reducer }: any): IStateProps => {
    return {
        user: reducer.get('user', null),
    };
};

export default connect(mapStateToProps, null)(MyLeftSidebar);
myRightSidebar.tsx
import React from 'react';
import { connect } from 'react-redux';
import CommonSidebar from '../../commons/sidebar/commonSidebar';

const sidebarParameters = {
    fetchApiParameter: 'right',
    reducerKey: 'rightSidebarButtons',
    position: 'right',
};

interface IStateProps {
    user: string;
}

type IProp = IStateProps;

class MyRightSidebar extends React.PureComponent<IProp> {
    constructor(props: IProp) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick(params: any) {
        alert('do want you want. my params: ' + params);
    }

    render() {
        const { user } = this.props;

        return (
            <>
                {user !== null &&
                <CommonSidebar
                    handleOnClick={this.handleClick}
                    sidebarParameters={sidebarParameters}
                />
                }
            </>
        );
    }
}

const mapStateToProps = ({ reducer }: any): IStateProps => {
    return {
        user: reducer.get('user', null),
    };
};

export default connect(mapStateToProps, null)(MyRightSidebar);
reducerActionTypes.ts
export const SET_SIDEBAR_BUTTONS = 'SET_SIDEBAR_BUTTONS';
export const SET_USER = 'SET_USER';
reducer.ts
import I from 'immutable';
import { SET_SIDEBAR_BUTTONS, SET_USER } from '../static/reducerActionTypes';

interface Action {
    type: string;
    data: any;
    user: string;
}

export default (state: any = I.Map(), action: Action) => {
    switch (action.type) {

        case SET_USER:
            return state.set('user', action.user);

        case SET_SIDEBAR_BUTTONS:
            const { data: { key = '', buttons = I.Map() } = {} } = action;
            return state.set(key, buttons);

        default:
            return state;
    }
};
commonSidebar.tsx
import React from 'react';
import I from 'immutable';
import { connect } from 'react-redux';
import { Sidebar } from 'primereact/sidebar';
import  { CommonSidebarButton } from './commonSidebarButton';
import { getSidebarButtons } from '../../apis/sidebarAPI';
import { SET_SIDEBAR_BUTTONS } from '../../static/reducerActionTypes';
import 'primereact/resources/themes/nova-light/theme.css';
import 'primereact/resources/primereact.min.css';
import './commonSidebar.scss';

interface ISidebarParameters {
    fetchApiParameter: string;
    reducerKey: string;
    position: string;
}

interface IOwnProps {
    handleOnClick: (params: object) => void;
    sidebarParameters: ISidebarParameters;
}

interface IDispatchProps {
    setSidebarButtons: (buttons: any) => void;
}

interface IStateProps {
    sidebarButtons: any;
    user: string;
}

type IProp = IOwnProps & IDispatchProps & IStateProps;

class CommonSidebar extends React.PureComponent<IProp> {
    constructor(props: IProp) {
        super(props);
        this.renderButtons = this.renderButtons.bind(this);
    }

    async componentDidMount() {
        const { setSidebarButtons, sidebarParameters, user } = this.props;
        const buttons = await getSidebarButtons(sidebarParameters.fetchApiParameter, user);
        setSidebarButtons(buttons);
    }

    componentWillUnmount(): void {
        const { setSidebarButtons } = this.props;
        setSidebarButtons(I.Map());
    }

    renderButtons() {
        const { sidebarButtons } = this.props;
        const isSuccess = I.List.isList(sidebarButtons);
        const sortedSidebarButtons = isSuccess && sidebarButtons.sortBy((s: any) => s.get('orderNo'));

        return(
            <div >
                {isSuccess &&
                sortedSidebarButtons.map((button:any, idx: number) => (
                    <CommonSidebarButton
                        button={button}
                        handleOnClick={this.props.handleOnClick}
                        key={idx}
                    />
                ))
                }
            </div>
        );
    }

    render() {
        const { position } = this.props.sidebarParameters;

        return(
            <Sidebar
                className="common-sidebar"
                modal={false}
                visible
                onHide={() => null}
                showCloseIcon={false}
                baseZIndex={1}
                position={position}
            >
                {this.renderButtons()}
            </Sidebar>
        );
    }
}

const mapStateToProps = ({ reducer }: any, ownProps: IOwnProps): IStateProps => {
    return {
        sidebarButtons: reducer.getIn([ownProps.sidebarParameters.reducerKey, 'data'], I.List()),
        user: reducer.get('user', ''),
    };
};

const mapDispatchToProps = (dispatch: any, ownProps: IOwnProps): IDispatchProps => ({
    setSidebarButtons: (data: any) => {
        dispatch({
            data: { buttons: data, key: ownProps.sidebarParameters.reducerKey },
            type: SET_SIDEBAR_BUTTONS,
        });
    },
});

export default connect<IStateProps, IDispatchProps, IOwnProps>(
    mapStateToProps,
    mapDispatchToProps
)(CommonSidebar);
commonSidebarButton.tsx
import React from 'react';
import { Button } from 'primereact/button';
import 'primereact/resources/themes/nova-light/theme.css';
import 'primereact/resources/primereact.min.css';
import 'primeicons/primeicons.css';
import './commonSidebar.scss';

export const CommonSidebarButton = ({ button, handleOnClick }: any) => (
    <Button
        label={button.get('iconLabel')}
        icon={button.get('iconName')}
        onClick={() => handleOnClick(button.get('payload'))}
    />
);
commonSidebar.scss
body {
  div {
    .common-sidebar {
      background: #2c7f33;
      width: 70px;
    }
  }
}

body {
  .p-sidebar {
    border: 0px ;
    padding:0px;
  }

  .p-button {
    background-color: transparent;
    border-color: #2c7f33;
    color: #ffffff;
    font-size: 12px;
    padding: 10px 5px;
    margin-top: 10px;
  }

  .p-button.p-button-icon-only {
    width: 100%;
  }

  .pi {
    font-size: 3.00em;
  }

  .p-button.p-button-text-icon-left .p-button-text {
    padding: 0px;
  }

  .p-button.p-button-icon-only .p-button-text {
    display: none;
  }

  .p-button:enabled:active {
    background-color: #1b9e1c;
    border-color: #ffffff;
  }

  .p-button:enabled:focus {
    box-shadow: 0 0 0 0.1em red;
  }

  .p-button:enabled:hover {
    background-color: #1b9e1c;
    border-color: #ffffff;
  }
}

.p-button-icon-only .p-button-icon-left, .p-button-text-icon-left .p-button-icon-left {
  position: initial;
}

.p-button-text {
  color: #ffffff;
  font-size: 9px;
}

.p-button-icon-only .p-button-icon-left{
  margin-top: 0px;
  margin-left: 0px;
}
sidebarAPI.ts
import axios from 'axios';
import I from 'immutable';

export const getSidebarButtons = async(sidebarType: string, user: string) => {
    try {
        const { data } = await axios.get(
            `http://localhost.../getSidebarButtons?sidebarType=${sidebarType}&user=${user}`);
        return I.fromJS({ data });

    } catch (e) {
        return I.fromJS({
            data: {
                error: 'Error while fetching sidebar buttons',
            },
        });
    }
};
For this dynamic loading a rest api has called. It takes 2 parameter -sidebarType, user- to decide which parameters should return.
An example of  rest api result: (sidebarType is 'left')
[{
"id":"1","orderNo":"2","iconName":"pi pi-bell",
  "iconLabel":"Give Your Icon Label If You Want",
  "payload":{"params":{"componentPath":"/test"}}
},
{
"id":"2","orderNo":"3","iconName":"pi pi-check",
  "payload":{"params":{"componentPath":"/test"}}
},
{
"id":"3","orderNo":"1","iconName":"pi pi-times",
  "iconLabel":"Give Your Icon Label If You Want",
  "payload":{"params":{"componentPath":"/test"}}
}]
for sidebarType = 'right'
[{
"id":"1","orderNo":"2","iconName":"pi pi-bell",
  "iconLabel":"Give Your Icon Label If You Want",
  "payload":{"params":{"componentPath":"/test"}}
}]

Thursday

Fragments in React (No more unnecessary nodes in the DOM)

React.Fragment advantages:
- return elements without any extra div or any other tags
- return a list of child without having a parent node. No more wrapping elements.

Requirements:
- Babel v7.0.0-beta.31 and above
- React v16.2.0 and above

Normally you can not the following, you have to wrap it.
import React, { Component } from 'react';

class FragmentExample extends Component {
  render() {
      return (
          <li>One</li>
          <li>Two</li>
      );
    }
  }
  
export default FragmentExample;

Before react@16, you have to wrap with any tag like <ul> || <span>.
But no need anymore with Fragment.
import React, { Component, Fragment } from 'react';

class FragmentExample extends Component {
  render() {
      return (
        <Fragment>
          <li>One</li>
          <li>Two</li>
        </Fragment>
      );
    }
  }
  
export default FragmentExample;

Short syntax:
class FragmentExample extends Component {
  render() {
      return (
        <>
          <li>One</li>
          <li>Two</li>
        </>
      );
    }
  }
  
export default FragmentExample;

Wednesday

How to use enums as props in react with typescript

myConstants.ts
export enum SIZE_TYPES {
  FULL = 'full',
  SMALL = 'small',
}

myClass.tsx
.
.
import { SIZE_TYPES } from '../static/myConstants';

interface Prop {
  sizeType: SIZE_TYPES;
}

class MyClass extends React.PureComponent<Prop> {
 .
 .
}

myClass2.tsx
.
.
import { SIZE_TYPES } from '../static/myConstants';

class MyClass2 extends React.PureComponent {
  render() {
    return (
        <MyClass sizeType={SIZE_TYPES.FULL}/>
    );
  }
}

Thursday

jquery dialog example

HTML:
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>position demo</title>
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="https://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
</head>

<body>
 <table id="table">
   <tr>
     <td style="padding:0px 0px; border-top:0px 0px; width:100%;">
        <div id="header">Header</div>
     </td>
     <td rowspan="2" style="padding:0px 0px 0px; border-top:0px; width:100%;">
         <div id="sidebar" >
           Sidebar
         </div>
      </td>
  </tr>
   <tr>
      <td style="width: 100%;padding:0px 0px 0px; border-top:0px; width:100%;">
        <div id="content" >
           <button type="button" id="opener1">Open the dialog full</button>
           <button type="button" id="opener2">Open the dialog half</button>
        </div>
      </td>
   </tr>
 </table>

   <div id="dialog" >Dialog</div>
    
</body>
</html>
CSS:
#dialog {   
    background: green;
    font-size: 24pt;
    text-align: center;
}

#header {
  border: solid 1px;
  height: 20px;
  width: 100%;
  margin-top: 20px;
}

#content {
  border: solid 1px;
  margin-top: 0px;
  margin-right: 0px;
  height: 300px;
  width: 100%;
}

#sidebar {
  border: solid 1px;
  margin-top: 20px;
  margin-left: 0px;
  height: 324px;
  width: 55px;
}

.ui-dialog-titlebar-close, .ui-dialog-titlebar {
  display: none;
}

.ui-dialog {
    z-index: 999999 !important ;
    margin-left: 0px;
}

.ui-dialog, .ui-dialog-content {
    box-sizing: content-box;
}
JS:
 function closeDilalogIfClickedOutside(event) {
    if($('#dialog').dialog('isOpen')
        && !($('#dialog')).is(event.target)
        && $('#dialog').has(event.target).length == 0 ) {
            $('#dialog').dialog('close');
    }
}

$(window).on("click", function(event){   
    closeDilalogIfClickedOutside(event);
});

function catchOutsideClickEvent() {
    var i;
    for(i = 0; i < (window.frames).length; i++) {
        try {
            var win = window.frames[i];
            if(win.frameElement.id != 'dialogIframe') {
                $(win).on("click", function(event){   
                    closeDilalogIfClickedOutside(event);
                });         
            }
        } catch(err) {
            console.log("frame: " + i + " y:" + y + " err: " + err);
        };
    };
}
$(document).ready(function () {
  $(function() {
    $("#dialog").dialog({
        autoOpen: false, 
        modal: false,
        hide: {effect:"slide", direction:"right", duration: 700},
        show : {effect:"slide", direction:"right", duration: 700},
        open: function(event, ui) {
            catchOutsideClick();
        }
    });
  });
});

function resizeDialog(sizeType) {
    var relativeDiv, relativeHeight, relativeWidth, relativeMy;

    if(sizeType == 'full') {
        relativeDiv = '#sidebar';
        relativeHeight = $('#sidebar').height();
        relativeWidth = '200';
        relativeMy = 'left top';

    } else {
        relativeDiv = '#content';
        relativeHeight =  $('#content').height();
        relativeWidth = $(window).width() / 2;
        relativeMy = 'right top';
    }

    $("#dialog").dialog({
        width:relativeWidth,
        height:relativeHeight,
        position: {
            my: relativeMy,
            at: relativeMy,
            of: relativeDiv
        }
    });
}

$('#opener1').click(function() {
      resizeDialog("full");
      $("#dialog").dialog("open");
});

$('#opener2').click(function() {
      resizeDialog("half");
      $("#dialog").dialog("open");
});


var resizeId;
$(window).bind('resize', function(event) {
    if($('#dialog').dialog('isOpen') && !$(event.target).hasClass('ui-resizable')){
      clearTimeout(resizeId);
      resizeId = setTimeout(resizeDialog, 250);
    }
});


Monday

postMessage API >> send messages & call parent's js function: between jsp and react app (in iframe)

I tried to:
- open a react app in an iframe from jsp
- send message by postMessage API>> from jsp to react, from react to jsp
- call parent's function by postMessage API inside iframe(react app)

http://localhost:8080 >> jsp 
http://localhost:3000 >> react

jsp example:
 ....
<tiles:put name="body" type="string">
   
 <div id="reactIframeLoading" style="height:50px; color:red; font-size:12px; 
      margin-left:2px;">
      React Iframe Loading...<br> 
      <a href="javascript:loadReactIframe()">Retry</a>
 </div> 

 <iframe 
      id="reactIframe" 
      style="display:none;"
      onload="reactIframePostMessage(); reactIframeLoaded();"
      src="http://localhost:3000/"
      width="100%" height="200" border="0" marginwidth="0"
      marginheight="0" scrolling="no">
 </iframe> 
  
 <script type="text/javascript">    
     const dataForReactPostMessage = {
           isReadOnly: false,
           someData: {
               someDataChild: 'eda'
          }
      }

     function callMeFromReact(msg) {
         console.log('callMeFromReact: params: ' + msg);
     }
  
     function reactIframeLoaded() {
        document.getElementById("reactIframe").style.display='';
        document.getElementById("reactIframeLoading").style.display='none';
     }  
  
     function loadReactIframe(){
         document.getElementById("reactIframe").src="http://localhost:3000/";
     }
  
     function reactIframePostMessage(){
         document.getElementById("reactIframe").contentWindow.postMessage(
              dataForReactPostMessage, 'http://localhost:3000/'
         );
     }
  
    window.addEventListener('message', handleFrameTasks);

    //get messages from iframe or run function given by iframe  
     function handleFrameTasks(event) {
           if(event.origin !== "http://localhost:3000") {
              return;
           }

           //if function is given
           var data = event.data;
           if(typeof(window[data.func]) == "function") {
                 window[data.func].call(null, data.params[0]);

          //if data is given
          } else if(data.event_id === 'my_first_message') {
                console.log('post message from react to jsp // event_id: my_first_message= ' + JSON.stringify(event.data));
          }
     }
  </script>
</tiles:put>

react example:
import React, { Component } from 'react'

class Example extends Component {

    constructor(props) {
        super(props);
        this.handleFrameTasks = this.handleFrameTasks.bind(this);
        this.sendParentPostMessage = this.sendParentPostMessage.bind();
    }

    componentWillMount() {
        window.addEventListener('message', this.handleFrameTasks);
    }

    componentWillUnmount() {
        window.removeEventListener("message", this.handleFrameTasks);
    }

    handleFrameTasks(event) {
        if(event.origin !== "http://localhost:8080") {
           return;
        }
        console.log('postmessage from jsp to react // event.data= ' + JSON.stringify(event.data));
    }

    sendParentPostMessage() {
        const dataForJspPostMessage = {
            event_id: 'my_first_message',
            someData: {
                someDataChild1: 'eda 1', 
                someDataChild2: 'eda 2'
            }
        } 
        //send data to parent
        window.parent.postMessage(dataForJspPostMessage, 'http://localhost:8080'); 

        //call js function named as 'callMeFromReact' in parent
        window.parent.postMessage(
            {'func':'callMeFromReact','params':['SomeMessages']}, 
            'http://localhost:8080'
        ); 

        window.parent.postMessage(
            {'func':'nonExistingMethod','params':['SomeMessages']}, 
            'http://localhost:8080'
        );
    }

    render() {
        return (
            <div>
                <h1>Hello, world!</h1>
                <button onClick={this.sendParentPostMessage}>sendParentPostMessage</button>
            </div>
        );
    }

}

export default Example

UPDATE: last version for post message listener:
window.addEventListener('message',  function (event) {
      if(event.origin != null && event.origin.includes(".int.teb.com.tr")) {
            var data = event.data;
            if(data != null && typeof(window[data.func]) == "function"){
                if(data.params != null && data.params.length > 1) {
                  var args = new Array();
                  for(var i = 0; i < data.params.length; i++){
                       args.push(data.params[i]);
                  }

                  window[data.func].apply(this, args);
                  
                } else {
                  window[data.func].call(null, data.params);
                }
            }
      }
}); 

Javascript tips

Some important concepts:

1.  "hoisting" : Javascript moves all declarations to the top before executing the code. It other words, a variable can be used before it is declared.

Advice: If you want to avoid confusion, declare variables at the beginning of the function.
Note: Javascipt does this only for declarations. Initializations aren't hoisting to the top.
<script>
    var x = 3;  
    elem = document.getElementById("demo");      
    elem.innerHTML = "x is " + x + " and y is " + y; 
    var y = 4;  
    //result: x is 3 and y is undefined
</script>



<script>
    var x = 3; 
    var y;
    elem = document.getElementById("demo");      
    elem.innerHTML = "x is " + x + " and y is " + y; 
    y = 4;  
    //result: x is 3 and y is undefined
</script>



<script>
    var x = 3; 
    var y = 4; 
    elem = document.getElementById("demo");      
    elem.innerHTML = "x is " + x + " and y is " + y; 
    //result: x is 3 and y is 4
</script>


<script>
    x = 3; 
    y = 4; 
    elem = document.getElementById("demo");      
    elem.innerHTML = "x is " + x + " and y is " + y; 
    var x, y;
    //result: x is 3 and y is 4
</script>

2.  
var a = 1 >> declares the variable in the current scope which can be local or global.
       a = 1 >> if the variable couldn't be found anywhere in the scope chain, it becomes global.This usage is very bad practice!!!

3.  Arrow functions aren't same with regular functions. 'this' keyword not bound to the element when it is used in arrow functions.
Try not to use arrow functions with constructors, click handlers, class/object methods!



react-booststrap-table example


npm install react-bootstrap-table --save
npm install bootstrap --save

import React from 'react';
import ReactDOM from 'react-dom';
import BootstrapTableTest from './bootstrap/BootstrapTableTest';
import './index.css';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<BootstrapTableTest />, document.getElementById('root'));

serviceWorker.unregister();

getSprintList rest service json example:

[{"sprintNo":"2","sprintBeginDate":"2019-04-15","sprintEndDate":"2019-04-15","active":"Y"},
{"sprintNo":"4","sprintBeginDate":"2019-04-15","sprintEndDate":"2019-04-15","active":"N"}]

 I used fetchings in the same class without separating to middleware layer, it is a simple example.
import React, { Component } from 'react'
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';
import '../../node_modules/bootstrap/dist/css/bootstrap.min.css';
import '../../node_modules/react-bootstrap-table/dist/react-bootstrap-table.min.css';

class BootstrapTableTest extends Component {
    constructor(props) {
        super(props)
        this.state = {
            sprints: [],
            error: null
        }
    }   

    componentDidMount() {
        fetch(`http://localhost:8080/agile/getSprintList`, {
            method: "GET"
        })
        .then(response => {
            console.log('sprint componentDidMount', response)
            if(response.ok) {
                console.log('Successfully fetch sprintList')
                return response.json();
            } else {
                throw new Error('Cant fetch sprint list. Something went wrong.')
            }
        })
        .then(data => 
            this.setState({sprints: data})
        )
        .catch(err => this.setState({error: err}))
    }

    updateRow(row, cellName, cellValue) {
        const rowJson = JSON.stringify({
            sprintNo: row.sprintNo,
            sprintBeginDate: row.sprintBeginDate,
            sprintEndDate: row.sprintEndDate,
            active: row.active
        })
        console.log('sprint updateRow', rowJson)

        fetch(`http://localhost:8080/agile/updateSprint`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: rowJson
        })
       .then(response => {
            console.log('sprint updateRow', response)
            if (response.ok) {
               console.log('Successfully updated sprint')
            } else {
               throw new Error('Somthing happened wrong while updating sprint')
           }
       })
       .catch(err => this.setState({error: err}))
    }

    addRow(row) {
        const rowJson = JSON.stringify({
            sprintNo: row.sprintNo,
            sprintBeginDate: row.sprintBeginDate,
            sprintEndDate: row.sprintEndDate,
            active: row.active
        })
        console.log('sprint addRow', rowJson)

        fetch(`http://localhost:8080/agile/addSprint`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: rowJson
        })
        .then(response => {
            console.log('sprint addRow', response)
            if (response.ok) {
               console.log('Successfully added sprint')
            } else {
               throw new Error('Somthing happened wrong while adding sprint')
            }
        })
        .catch(err => this.setState({error: err}))
    }

    deleteRow(rowKeys) {
        fetch(`http://localhost:8080/agile/deleteSprint?sprintNo=${rowKeys}`, {
            method: 'POST',
            headers: {
               'Content-Type': 'application/json'
            },
        })
        .then(response => {
            console.log('sprint deleteRow', response)
            if (response.ok) {
                console.log('Successfully removed sprint', rowKeys)
            } else {
               throw new Error('Somthing happened wrong while deleting sprint')
            }
        })
        .catch(err => this.setState({error: err}))
    }

    numericValidator(value, row) {
        const nan = isNaN(parseInt(value, 10))
        if(nan) {
            return 'Enter numeric values.'
        }
        return true;
    }

    createCustomModalHeader(onClose, onSave) {
        const headerStyle = {
            fontWeight: 'bold',
            padding: '2px 2px',
            margin: '5px',
            fontSize: 'medium',
            textAlign: 'center',
            display: 'initial',
            backgroundColor: '#eeeeee'
        };
        return (
            <div className='modal-header' style={ headerStyle }>
                <h3>Add New Sprint</h3>
            </div>
        );
    }

    render() {
        if(this.state.error) {
            return <p>{this.state.error.message}</p>
        }

        const jobTypes = [ 'Y', 'N' ];

        const selectRow = {
            mode: 'checkbox',
            clickToSelect: true
        };

        const cellEditProp = {
            mode: 'click',
            blurToSave: true,
            afterSaveCell: this.updateRow
        };

        const options = {
            afterDeleteRow: this.deleteRow,
            afterInsertRow: this.addRow,
            deleteText: 'Delete',
            insertText: 'Insert',
            paginationSize: 1,
            prePage: 'Previous',
            nextPage: 'Next',
            firstPage: 'First Page',
            lastPage: 'Last Page',
            defaultSortName: 'sprintNo',
            defaultSortOrder: 'desc',
            insertModalHeader: this.createCustomModalHeader
        };

        return(
            <BootstrapTable data={this.state.sprints} 
                striped hover pagination search multiColumnSearch ignoreSinglePage 
                selectRow={ selectRow }
                cellEdit={ cellEditProp }
                options={ options }
                height='750' scrollTop={ 'Bottom' }
                deleteRow insertRow 
                exportCSV csvFileName='sprint.csv'
            >
                <TableHeaderColumn 
                    isKey dataField='sprintNo' dataAlign='right' dataSort={ true }
                    editable={ {validator: this.numericValidator} } >
                    Sprint Number
                </TableHeaderColumn>
                <TableHeaderColumn  
                    dataField='sprintBeginDate' 
                    editable={ { type: 'date' } }>
                    Sprint Begin Date
                </TableHeaderColumn>
                <TableHeaderColumn  
                    dataField='sprintEndDate' 
                    editable={ { type: 'date' } }>
                    Sprint End Date
                </TableHeaderColumn>
                <TableHeaderColumn  
                    dataField='active' 
                    editable={ { type: 'select', options: { values: jobTypes } } }>
                    Is Active
                </TableHeaderColumn>
            </BootstrapTable >
        )
    }

}
export default BootstrapTableTest