I make a table containing some rules, i added a button so the user can edit any row onclicking on the edit button. i want to change the clicked row only not all rows. also i want to blur on the required row when the user click edit button.
const[isEditing, setIsEditing] = useState(false)
const onEditHandler = (event:any) =>{
const editedRuleId = (event.target.id);
setIsEditing(!isEditing);
}
<div className='container'>
{Object.entries(rules).map((rule) => (
<div key={rule[0]} className='tbl_rules'>
<div className='box-1'><h6>{rule[0]}</h6></div>
<div contentEditable={isEditing} className='box-2'>{rule[1]}</div>
<div className='box-3'>
<button
id={rule[0]}
type="button"
className="btn btn-sm btn-info"
onClick={onEditHandler}
>{isEditing ? 'Save' : 'Edit'}</button>
</div>
</div>
))}
</div>
CodePudding user response:
Best way to do this would be to make each row a unique component. So you would end up with code that looks like this:
<div className='container'>
{Object.entries(rules).map((rule) => (
<Rule rule={rule}>
))}
</div>
And in the Rule
component, you would add the rest of your code as follows which will allow each row to hold its own state:
const[isEditing, setIsEditing] = useState(false)
const onEditHandler = (event:any) => {
const editedRuleId = (event.target.id);
setIsEditing(!isEditing);
}
return (<div key={rule[0]} className='tbl_rules'>
<div className='box-1'><h6>{rule[0]}</h6></div>
<div contentEditable={isEditing} className='box-2'>{rule[1]}</div>
<div className='box-3'>
<button
id={rule[0]}
type="button"
className="btn btn-sm btn-info"
onClick={onEditHandler}
>
{isEditing ? 'Save' : 'Edit'}</button>
</div>
</div>);
CodePudding user response:
const [ selectedCell, setSelectedCell ] = useState(null) ;
<div className='container'>
{
Object.entries(rules).map( ([rule, id]) =>
return {
<div key={id} className='tbl_rules'>
{
rule.map((item, index) => {
<div className='box-1'
contentEditable={selectedCell === id "_" index}
onClick={() => setSelectedCell(id "_" index)}
>
{item}
</div>
})
}
</div>
}
)
}
</div>
# for example rules
{
row_1 : ["rule_1_1", "rule_1_2"],
row_2 : ["rule_2_1", "rule_2_2"]
}