Last active
February 11, 2021 11:13
-
-
Save c0d0g3n/ed630ea7a24ac8a3c4a09faab77aa7ec to your computer and use it in GitHub Desktop.
React: double click to edit, blur to save and exit.
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 from 'react' | |
import settings from '../settings.js' | |
import Field from '../styles/FieldStyle.jsx' | |
export default class EditableContainer extends React.Component { | |
constructor (props) { | |
super(props) | |
// init counter | |
this.count = 0 | |
// init state | |
this.state = { | |
edit: false, | |
} | |
} | |
componentWillUnmount () { | |
// cancel click callback | |
if (this.timeout) clearTimeout(this.timeout) | |
} | |
handleClick (e) { | |
// cancel previous callback | |
if (this.timeout) clearTimeout(this.timeout) | |
// increment count | |
this.count++ | |
// schedule new callback [timeBetweenClicks] ms after last click | |
this.timeout = setTimeout(() => { | |
// listen for double clicks | |
if (this.count === 2) { | |
// turn on edit mode | |
this.setState({ | |
edit: true, | |
}) | |
} | |
// reset count | |
this.count = 0 | |
}, settings.timeBetweenClicks) // 250 ms | |
} | |
handleBlur (e) { | |
// handle saving here | |
// close edit mode | |
this.setState({ | |
edit: false, | |
}) | |
} | |
render () { | |
const {children, ...rest} = this.props | |
const {edit} = this.state | |
if (edit) { | |
// edit mode | |
return ( | |
<Field | |
autoFocus | |
onBlur={this.handleBlur.bind(this)} | |
/> | |
) | |
} else { | |
// view mode | |
return ( | |
<span | |
onClick={this.handleClick.bind(this)} | |
{...rest} | |
> | |
{children} | |
</span> | |
) | |
} | |
} | |
} |
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 from 'react' | |
export default class FieldStyle extends React.Component { | |
componentDidMount () { | |
this.ref && this.ref.focus() | |
} | |
render () { | |
const {autoFocus, ...rest} = this.props | |
// auto focus | |
const ref = autoFocus ? (ref) => { this.ref = ref } : null | |
return ( | |
<input | |
ref={ref} | |
type="text" | |
{...rest} | |
/> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment