Created
September 4, 2019 11:47
-
-
Save kaungmyatlwin/ba8e3405a60c99c6e1beacc3cd96cb99 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 from "react"; | |
import ReactDOM from "react-dom"; | |
import EditableText from "./EditableText"; | |
import "./styles.css"; | |
function App() { | |
return ( | |
<div className="App"> | |
<h1>Editable Text Demo</h1> | |
<EditableText text="Kaung wtf Lwin" /> | |
</div> | |
); | |
} | |
const rootElement = document.getElementById("root"); | |
ReactDOM.render(<App />, rootElement); |
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 = props => { | |
// We use hooks to declare "initial" states | |
const inputRef = useRef(null); | |
const [inputVisible, setInputVisible] = useState(false); | |
const [text, setText] = useState(props.text); | |
function onClickOutSide(e) { | |
// Check if user is clicking outside of <input> | |
if (inputRef.current && !inputRef.current.contains(e.target)) { | |
setInputVisible(false); // Disable text input | |
} | |
} | |
useEffect(() => { | |
// Handle outside clicks on mounted state | |
if (inputVisible) { | |
document.addEventListener("mousedown", onClickOutSide); | |
} | |
// This is a necessary step to "dismount" unnecessary events when we destroy the component | |
return () => { | |
document.removeEventListener("mousedown", onClickOutSide); | |
}; | |
}); | |
return ( | |
<React.Fragment> | |
{inputVisible ? ( | |
<input | |
ref={inputRef} // Set the Ref | |
value={text} // Now input value uses local state | |
onChange={e => { | |
setText(e.target.value); | |
}} | |
/> | |
) : ( | |
<span onClick={() => setInputVisible(true)}>{text}</span> | |
)} | |
</React.Fragment> | |
); | |
}; | |
export default EditableInput; // We got our component! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment