Recently, I needed a user friendly component which can be editable when the user clicks on it. In this post I will show you how to do it with react hooks.
I used the onBlur and onFocus functions of the text area to handle edit and save mode.
import React, { useState } from "react";
export const EditBox = (props) => {
const maxChar = 500;
const rows = 10;
const [remainedChar, setRemainedChar] = useState(500);
const [isEditable, setEditable] = useState(false);
const handleChange = (e) => {
setRemainedChar(maxChar - e.target.value.length);
};
const handleFocus= (e) => {
setEditable( true);
}
const handleBlur = (e) => {
console.log( 'Saved:', e.target.value);
setEditable( false);
}
return (
<div className="editbox">
<div className="custom-label" >
<div className = "editbox-label">
{props.label}
</div>
</div>
<textarea
rows={rows}
maxLength={maxChar}
onChange={handleChange}
onBlur={handleBlur}
onFocus={handleFocus}
className={`editbox-textarea ${isEditable ? "text-edit active-box" : ""} `}
></textarea>
<div className={`edit-bottom d-flex justify-content-end text-detail ${isEditable ? "" : "invisible"}`}>
<i className="remained-char">
{remainedChar}/{maxChar}
</i>
</div>
</div>
);
};
export default EditBox;
I removed border and outline of the text-area since I want it to be seen like a box. I get the row number value as a prop and showed the remained-chars to the user, so I set the resize property to none because I did not need it.
/* EDITBOX --------------- */
.editbox {
margin-bottom: 1rem;
}
.editbox textarea {
font-family: inherit;
}
.editbox .edit-action {
text-decoration: underline;
font-size: 1rem;
font-weight: normal;
}
.editbox .editbox-textarea {
outline: none;
border: none;
color: var(--text-secondary);
width: 100%;
resize: none;
background-color: transparent;
border: 1px solid #C6CBD4;
border-radius: .5rem;
padding: 1rem;
transition: .2s;
}
.editbox .editbox-textarea:hover{ border: #9090cc .5px solid;}
.editbox .editbox-textarea:focus,
:active,
:visited {
outline: none;
}
.editbox .text-edit {
color: var(--text-secondary);
background-color: transparent;
font-weight: normal;
}
.editbox .edit-bottom { transform: translate(-.5rem, -1.5rem);}
Top comments (1)
Great explaination :)