Last active
June 23, 2018 08:16
-
-
Save abelaska/0ede1068450e10f99f38dcb68eaacd8e to your computer and use it in GitHub Desktop.
React Inline contenteditable
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
// @flow | |
/* global document */ | |
export default ({ | |
onCommit, | |
maxLength = -1, | |
state = {} | |
}: { | |
state?: { | |
originalValue?: string | |
}, | |
maxLength: number, | |
onCommit: (value: string) => void | |
}) => ({ | |
suppressContentEditableWarning: true, | |
contentEditable: 'plaintext-only', | |
onFocus: (e: Object) => { | |
state.originalValue = e.target.innerText; | |
}, | |
onKeyDown: (e: Object) => { | |
if (e.keyCode === 13) { | |
e.preventDefault(); | |
return e.target.blur(); | |
} | |
if (e.keyCode === 27) { | |
e.target.innerText = state.originalValue; | |
e.preventDefault(); | |
return e.target.blur(); | |
} | |
}, | |
onBlur: (e: Object) => { | |
if (e.target.innerText) { | |
if (onCommit && e.target.innerText !== state.originalValue) { | |
onCommit(e.target.innerText); | |
} | |
} else { | |
e.target.innerText = state.originalValue; | |
} | |
}, | |
onKeyPress: (e: Object) => { | |
if (maxLength > -1 && (e.target.innerText || '').length >= maxLength) { | |
return e.preventDefault(); | |
} | |
}, | |
onPaste: (e: Object) => { | |
e.preventDefault(); | |
const clipboard = e.clipboardData.getData('text'); | |
const text = clipboard && clipboard.replace(/\n/g, ''); | |
if (text) { | |
const pasteLen = Math.max(0, maxLength - (e.target.innerText || '').length); | |
const pasteText = maxLength > -1 ? pasteLen > 0 && text.substr(0, pasteLen) : text; | |
if (pasteText) { | |
document.execCommand('insertText', false, pasteText); | |
} | |
} | |
} | |
}); | |
// <div {...editable({ maxLength: 10, onCommit: value => console.log('new value', value)}>content to edit</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment