Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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