Skip to content Skip to sidebar Skip to footer

Highlight Textbox On Edit

In continuation to Question , if I have a row that is currently being edited (via state), how do I keep the input textbox highlighted only if edited and stays highlighted even afte

Solution 1:

There are a few ways you could achieve this - one way is to track additional state per student field to show highlighting in this way. One possiblitiy is to use a similar pattern to your current solution by means of the following:

render() {
    return (<table className="table-data">
 <tbody>
 <tr>
    <th>Name</th>
    <th>Age</th>
    <th>Class</th>
    <th>Section</th>
 </tr>   

 {  this.state.students.map((item,key) => {

    const editField = (value, index) => {

      // Clone students data before mutation
      const students = this.state.students.map(item => ({ ...item }))

      // Update field by index of current student
      students[key][index] = value

      // Extend state for student to tract editing history per field
      students[key].edited = students[key].edited || []
      students[key].edited[index] = true

      // Trigger re-render
      this.setState({ students })
    }

    // Returns true if the field by index has been edited. This is used for styling the td
    const isEdited = (index) => {
        const students = this.state.students.map(item => ({ ...item }))
        return (students[key].edited && students[key].edited[index] === true)
   }

   // Apply 'editing' class to the cell if it has been previously edited
   return (
    <tr key={key} className={ item.editing ? 'editing' : '' } onClick={()=> {

      // Clone students data before mutation
      const students = this.state.students.map(i => ({ ...i, editing : item.editing && i===item }))

      // Toggle editing flag of this current student (ie table row)
      students[key].editing = true; 

      // Trigger re-render
      this.setState({
        clientIsEditing:true, // This might not be needed ?
        students
      })
}
    }> 
    <td className={ isEdited(1) ? 'edited' : '' } >{ item.editing ? <input value={item[1]} onChange={ e => editField(e.target.value, 1) } /> : <span>{item[1]}</span> }</td>    
    <td className={ isEdited(2) ? 'edited' : '' } >{ item.editing ? <input value={item[2]} onChange={ e => editField(e.target.value, 2) } /> : <span>{item[2]}</span> }</td>    
    <td className={ isEdited(3) ? 'edited' : '' } >{ item.editing ? <input value={item[3]} onChange={ e => editField(e.target.value, 3) } /> : <span>{item[3]}</span> }</td>  
    <td className={ isEdited(4) ? 'edited' : '' } >{ item.editing ? <input value={item[4]} onChange={ e => editField(e.target.value, 4) } /> : <span>{item[4]}</span> }</td> 
    </tr>  )
  })
  }

  </tbody>
  </table>)
  }

To complete this, you would just need to add a CSS selector like this:

https://jsfiddle.net/7uspaot5/

For a working demo, please see this jsFiddle - hope this helps!


Post a Comment for "Highlight Textbox On Edit"