wesleybliss
3/13/2018 - 1:40 AM

Inline text element that switches to an input on click

Inline text element that switches to an input on click

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { SuiTextInput } from 'sui'

class InlineEditText extends Component {
    
    displayName: 'InlineEditText'
    
    state = {
        editMode: false,
        value: this.props.initialValue || ''
    }
    
    enableEditMode = () => {
        this.setState({ value: this.props.value || '' })
        this.setState({ editMode: true })
    }
    
    disableEditMode = () => {
        
        this.setState({ editMode: false })
        
        // Let the parent know the data has been changed
        if (this.props.value !== this.state.value)
            this.props.onChange(this.state.value)
        
    }
    
    handleSubmit = (e) => {
        e.preventDefault()
        this.disableEditMode()
    }
    
    renderNormalMode = () => (
        <span onClick={this.enableEditMode}>
            { this.props.value }
        </span>
    )
    
    renderEditMode = () => {
        
        const { value, onChange, ...passThroughProps } = this.props
        
        return (
            <form onSubmit={this.handleSubmit}>
                <SuiTextInput
                    autoFocus
                    type="text"
                    className="form-control"
                    value={this.state.value}
                    onChange={e => this.setState({ value: e.target.value })}
                    onBlur={this.disableEditMode}
                    {...passThroughProps}
                />
            </form>
        )
        
    }
    
    render() {
        
        return this.state.editMode
            ? this.renderEditMode()
            : this.renderNormalMode()
        
    }
    
}

InlineEditText.defaultProps = {
    initialValue: '',
    value: ''
}

InlineEditText.propTypes = {
    initialValue: PropTypes.string,
    value: PropTypes.string.isRequired,
    onChange: PropTypes.func.isRequired
}

export default InlineEditText