Skip to content

Instantly share code, notes, and snippets.

@Vinlock
Last active May 29, 2020 17:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Vinlock/95c5f3a756abc3272fc9ca7ac33185b4 to your computer and use it in GitHub Desktop.
Save Vinlock/95c5f3a756abc3272fc9ca7ac33185b4 to your computer and use it in GitHub Desktop.
Controlled Content Editable Div
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