Skip to content

Instantly share code, notes, and snippets.

@kaungmyatlwin
Created September 4, 2019 10:31
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 kaungmyatlwin/fab3d9e5ee02b84a0d0bf99d86a80f87 to your computer and use it in GitHub Desktop.
Save kaungmyatlwin/fab3d9e5ee02b84a0d0bf99d86a80f87 to your computer and use it in GitHub Desktop.
import React, { useState, useRef,useEffect } from 'react';
const EditableInput = ({
onChange,
text,
placeholder,
}) => {
const inputRef = useRef(null);
const [inputVisible, setInputVisible] = useState(false);
function onClickOutSide(e) {
if (inputRef.current && inputRef.current.contains(e.target)) {
setInputVisible(false);
};
}
useEffect(() => {
if (inputVisible) {
document.addEventListener('mousedown', onClickOutSide);
}
return () => {
document.removeEventListener('mousedown',onClickOutSide)
}
});
return (
<React.Fragment>
{
inputVisible ?
(<input ref={inputRef} value={text} placeholder={placeholder} onChange={onChange} />)
:
(<span onClick={() => setInputVisible(true)}>{text}</span>)
}
</React.Fragment>
);
};
export default EditableInput;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment