Created
July 17, 2017 05:24
-
-
Save ernestofreyreg/868d3ae89180a618cd8bf20aeef744e1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import PropTypes from 'prop-types' | |
import connect from 'react-setstate-connect' | |
const CHANGE_VALUE = 'CHANGE_VALUE' | |
const STOP_CHANGING = 'STOP_CHANGING' | |
const START_CHANGING = 'START_CHANGING' | |
const initialState = { | |
editing: false, | |
changedValue: null | |
} | |
const reducer = (state, action) => { | |
switch (action.type) { | |
case START_CHANGING: return {...state, editing: true, changedValue: action.value} | |
case CHANGE_VALUE: return {...state, changedValue: action.value} | |
case STOP_CHANGING: return {...state, editing: false} | |
} | |
return state | |
} | |
const createActions = ({getState, dispatch}) => ({ | |
startEditing: value => () => dispatch(START_CHANGING, {value}), | |
stopEditing: () => dispatch(STOP_CHANGING), | |
changeValue: ev => dispatch(CHANGE_VALUE, {value: ev.target.value}), | |
checkEndChanging: modifyValue => ev => { | |
if (ev.key === 'Enter') { | |
return dispatch(STOP_CHANGING) | |
.then(() => modifyValue(getState().changedValue)) | |
} | |
} | |
}) | |
const EditableCell = ({ | |
value, | |
modifyValue, | |
editing, | |
changedValue, | |
changeValue, | |
startEditing, | |
stopEditing, | |
checkEndChanging | |
}) => ( | |
<div className='EditableCell'> | |
{!editing && | |
<div className='value' onClick={startEditing(value)}> | |
{value} | |
</div> | |
} | |
{editing && | |
<div className='editor'> | |
<input | |
type='text' | |
value={changedValue} | |
onChange={changeValue} | |
onKeyPress={checkEndChanging(modifyValue)} | |
autoFocus | |
/> | |
</div> | |
} | |
</div> | |
) | |
EditableCell.propTypes = { | |
value: PropTypes.string.isRequired, | |
modifyValue: PropTypes.func.isRequired, | |
} | |
export default connect(EditableCell, reducer, createActions, initialState) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment