Created
September 4, 2019 10:31
-
-
Save kaungmyatlwin/fab3d9e5ee02b84a0d0bf99d86a80f87 to your computer and use it in GitHub Desktop.
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
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