Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get edited row data on click

I am new to ReactJS and I've been having some trouble of getting ReactTable working.

I've defined Cells to be editable like this:

const [editing, setEditing] = useState(null);   

const columns = [{
  Header: 'Brand',
  accessor: 'brand',
  Cell: props => editableCell(props)
}]

const editableCell = props => {
 return (editing !== null && editing.index === props.index) ? (<div
  contentEditable="true"
  suppressContentEditableWarning>
   {props.value}
 </div>) : props.value;
}

return (
 <ReactTable
  data={cars} 
  columns={columns} 
  pages={pages}
  loading={loading}
  defaultPageSize={pageSize}
  className="-striped -highlight"/>
);

const edit = row => {
 if(editing !== null && editing.index !== row.index){
  return;
 }
 setEditing(row);
}

const save = () => {
 console.log(editing); // should return edited data, but returns old data, because data doesn't update when user modifies each cell.
}

How do I get new data from the edited row upon save? Do I have to create a listener that changes the values to state while typing? I know why it doesn't work, but I don't know what or how to implement.

like image 853
Skege Avatar asked Mar 31 '26 09:03

Skege


1 Answers

Your could use onBlur() event for contentEditable div and inside onBlur event you can get value using e.target.innerHTML or e.target.innerText.

And inside of this editableCell function you will get you data using props.original. Using this props.original you can find your data from the state and after that if you want to update the data into state then you can do easily.

Please check below code and working stackblitz demo.

editableCell(props) {
    return (
      <div
        className={"edittable"}
        contentEditable
        suppressContentEditableWarning
        onBlur={e => {
          console.log(`original value : ${JSON.stringify(props.original)}`)
          const data = [...this.state.data];
          let row = data.find(o=>o.id == props.original.id);
          row[props.column.id] = e.target.innerHTML;
          console.log(`upated row value : ${JSON.stringify(row)}`)
        }}
        dangerouslySetInnerHTML={{
          __html: this.state.data[props.index][props.column.id]
        }}
      />
    );
}
like image 125
Narendra Jadhav Avatar answered Apr 03 '26 01:04

Narendra Jadhav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!