Last active
May 29, 2020 17:30
-
-
Save Vinlock/95c5f3a756abc3272fc9ca7ac33185b4 to your computer and use it in GitHub Desktop.
Controlled Content Editable Div
This file contains 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' | |
const EditableReactiveDiv = (props) => { | |
const { value: propsValue, onChange: propsOnChange, ...rest } = props | |
const [currentValue, setCurrentValue] = React.useState(propsValue) | |
const divRef = React.useRef(null) | |
React.useEffect(() => { | |
if (document.activeElement !== divRef.current) { | |
divRef.current.innerHTML = propsValue | |
} | |
}, [propsValue]) | |
React.useEffect(() => { | |
propsOnChange(currentValue) | |
}, [currentValue]) | |
React.useEffect(() => { | |
if (divRef.current) { | |
const onInput = (event) => { | |
setCurrentValue(event.target.innerHTML) | |
} | |
divRef.current.addEventListener('input', onInput) | |
return () => { | |
divRef.current.removeEventListener('input', onInput) | |
} | |
} | |
}, [divRef]) | |
return ( | |
<StyledDiv ref={divRef} contentEditable {...rest} /> | |
) | |
} | |
EditableReactiveDiv.defaultProps = { | |
onChange: () => {}, | |
value: '', | |
} | |
EditableReactiveDiv.propTypes = { | |
onChange: PropTypes.func, | |
value: PropTypes.string, | |
} | |
export default EditableDiv |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment