Skip to content

Instantly share code, notes, and snippets.

@kaungmyatlwin
Last active September 4, 2019 11:48
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/87f947b971a2ad777f4e0fde134893a8 to your computer and use it in GitHub Desktop.
Save kaungmyatlwin/87f947b971a2ad777f4e0fde134893a8 to your computer and use it in GitHub Desktop.
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 Myat Lwin" />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
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