JSFiddle - React, Tailwind, and code Playground

by ecropolis

JavaScript

import React, { Component } from 'react'

export default class Editable extends Component {
    constructor(props){
        super(props);
        this.state = {
            fieldEdit: false,
            inputValue: props.value
        };
        this.toggleEdit = this.toggleEdit.bind(this);
        this.handleInput = this.handleInput.bind(this);
    }
    toggleEdit(){
        if(this.state.fieldEdit === false){
            this.setState({ fieldEdit: true });
        } 
        // else {
        //     this.setState({ fieldEdit: false });
        // }
    }

    handleInput(e){
        this.setState({ ...this.state, inputValue: e.target.value });
    }

    render() {
        if(this.props.editMode)
            return (
                <div onClick={this.toggleEdit}>
                    <div className="editable">
                        <label>{this.props.label}</label>
                        { this.state.fieldEdit ? 
                            <div className="form-group">
                                <input name={this.props.name} value={this.state.inputValue} onChange={this.handleInput}/> 
                                <i>save</i>
                            </div>
                        : 
                            <span>{this.props.value}</span>        
                        }
                    </div>
                </div>
            )
        else if(this.props.value && !this.props.editMode)
            return (
                <div className="view-group">
                    <span className="label"></span>
                    <span>{this.props.value}</span> 
                </div>
            )
        else
            return null;
    }
}