Created
February 19, 2020 01:27
-
-
Save DrewWeth/855da8d496ca2dd464430275f96f5224 to your computer and use it in GitHub Desktop.
This file contains 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} from 'react'; | |
import { Input, Icon } from 'semantic-ui-react' | |
export const FocusEditableInput = (props) => { | |
const [state, setState] = useState ({ | |
hovering: false, | |
focused: false, | |
value: props.value || "" | |
}) | |
const onMouseEnter = () => { | |
setState({ ...state, hovering: true }); | |
} | |
const onMouseLeave = () => { | |
setState({ ...state, hovering: false }); | |
} | |
const onClick = (e) => { | |
e.stopPropagation(); | |
setState({ ...state, focused: true, hovering: false }); | |
} | |
const onBlur = () => { | |
const { onChange } = props; | |
const { value } = state; | |
setState({ ...state, focused: false, hovering: false }); | |
if (onChange) onChange(value); | |
} | |
const onKeyPress = (e) => { | |
if (event.key === "Enter") this.onBlur(); | |
} | |
const onChange = (e) => { | |
setState({ ...state, value: e.target.value }); | |
} | |
return ( | |
const { editable } = props; | |
const { focused, hovering, value } = state; | |
if (editable && focused) { | |
return ( | |
<Input | |
autoFocus | |
size="mini" | |
value={value} | |
onBlur={onBlur} | |
onChange={onChange} | |
onKeyPress={onKeyPress} | |
className="slim" | |
/> | |
); | |
} else { | |
return ( | |
<span | |
onClick={onClick} | |
onMouseEnter={onMouseEnter} | |
onMouseLeave={onMouseLeave} | |
style={{ display: "inline-block", minWidth: 60 }} | |
> | |
{value} | |
{editable && hovering && <Icon name="pencil alternate" style={{ fontSize: 16 }} />} | |
</span> | |
); | |
} | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment