score:1
Accepted answer
you need some way of being able to identify the row being edited, and a place to save the current edited data. that can be achieved by using state.
when the id of an object in your data array matches the current selected row (after you've clicked the edit button) return one set of row data that includes input
elements. if the id doesn't match, return normal row data.
here's a minimal working example.
const { usestate } = react;
const data = [
{ id: 1, name: 'rita', age: 22 },
{ id: 2, name: 'sue', age: 42 },
{ id: 3, name: 'bob', age: 12 }
]
function example({ data }) {
// have states for the data, the current selected row
// and the data that is currently being edited
const [ rowdata, setrowdata ] = usestate(data);
const [ selectedrow, setselectedrow ] = usestate(0);
const [ editdata, seteditdata ] = usestate({});
// compiles the row data
function getrows() {
return rowdata.map((obj, i) => {
// get the id, name, and age from the
// current object
const { id, name, age } = obj;
// if the id of the current object equals
// the selected row return a set of row data with input
// elements (not id though) auto-populated with the
// information from that object
if (id === selectedrow) {
return (
<tr>
<td>{editdata.id}</td>
<td>
<input
classname="edit"
type="text"
name="name"
value={editdata.name}/>
</td>
<td>
<input
classname="edit"
type="text"
name="age"
value={editdata.age}
/>
</td>
<button
data-id={id}
data-action="save"
>save
</button>
</tr>
);
}
// otherwise return a set of non-editable
// row data
return (
<tr>
<td>{id}</td>
<td>{name}</td>
<td>{age}</td>
<button
data-id={id}
data-action="edit"
>edit
</button>
</tr>
);
});
}
// when a button has been clicked
// note: because we're using event delegation
// (attaching listeners to the table element instead
// of all the rows) we need to check that element
// we clicked on is the button
function handleclick(e) {
const { nodename } = e.target;
if (nodename === 'button') {
const { id, action } = e.target.dataset;
// if the button action is edit, set the
// selected row state, and auto-populate the
// editdata state
if (action === 'edit') {
setselectedrow(+id);
const obj = data.find(obj => obj.id === +id);
seteditdata({...obj});
}
// if the action is save filter out the matching
// object from the data state, and then update the data
// with the filtered object, plus the object in
// the editdata state, making sure you sort by id
// otherwise the edited row will appear at the bottom
// then reset the states
if (action === 'save') {
const filtered = data.filter(obj => obj.id !== selectedrow);
const updated = [...filtered, editdata];
updated.sort((a, b) => a.id - b.id);
setrowdata(updated);
setselectedrow(0);
seteditdata({});
}
}
}
// when an input changes
// again we need to check that the element
// that has changed is an input
function handlechange(e) {
const { nodename } = e.target;
// update the editdata state using the input
// name and value
if (nodename === 'input') {
const { name, value } = e.target;
seteditdata({ ...editdata, [name]: value });
}
}
// we attach two listeners to the table element
// one to catch clicks from the button
// the other to catch changes to the inputs if
// we're in edit mode
return (
<table
onclick={handleclick}
onchange={handlechange}
>
<tr class="heading">
<td>id</td>
<td>name</td>
<td>age</td>
</tr>
<tbody>
{getrows()}
</tbody>
</table>
);
};
reactdom.render(
<example data={data} />,
document.getelementbyid('react')
);
table { border: 1px solid #898989; border-collapse: collapse; }
td, input { width: 75px; text-align: center; }
td { padding: 0.2em; border: 1px solid #898989; }
.heading { background-color: #efefef; text-align: center; font-weight: 600; }
.edit { background-color: #ffffcc; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Source: stackoverflow.com
Related Query
- making fields editable in row in reactjs
- Add edit fields on table row on click in reactjs without using react-table library
- ReactJS fields are not editable for Dynamic Fields
- How to get a onClick to work in a row - reactjs
- how to add row to a table using ReactJS on button click
- How to disable form submit button until all input fields are filled?! ReactJS ES2015
- How to make the row editable when clicking on an "Edit" button on a cell with react-table
- Gantt editable chart for ReactJs
- How to dynamically generate pair of input fields using reactjs
- Adding a EDIT button on the same row of the DetailsLists component in Office-ui-Fabric - ReactJS
- Making parallel async await calls in ReactJS
- Reactjs and Flexbox: Wrapping divs in render function making flex hard
- How to handle multiple onChange function from multiple input fields in Reactjs
- material-table Make Row Editable on Click
- How to pass Props() value into setState() to make modal form editable using ReactJs
- Make whole row clickable in reactJs
- Render grid items in one row - ReactJS and Material-UI
- Populate input fields from axios response reactjs
- How to make just 1 row editable in material-table?
- show and hide fields according to dropdown list in ReactJS
- Add Form Fields Dynamically -- ReactJs
- ReactJS: Express API and ReactJS Structure Limit ShowData per Row
- How to connect a ReactJS Form to a Django model to automatically obtain fields (foreignkeys, choices etc.)
- Fields are not editable using React Hook Form
- Single onChange function for multiple input fields is not working: ReactJS
- Add row to existing table dynamically in ReactJS
- How do I make sure null and empty string fields arent added to my documents in firestore Reactjs
- Reactjs -- making api request based on check/uncheck of checkbox not understanding properly
- ReactJS adding a data to a specific row from my custom table
- React - edit profile -first display read only fields and click on edit make fields editable
More Query from same tag
- success actions runs multiple times
- React pass dynamic state to all routes in router
- Display minuten from TimeStamp (React, TimeStamp, Firestore)
- Promise rejected in POST login using fetch API in reactjs and Nodejs
- the logout component not rendering after the authenticated is turned to true this is similar code as from react-router docs
- flex not wokring in html css
- replace comma with dot on fly
- Should I use React Router redirect OR package.json "homepage" property for setting a relative path as homepage in my React app
- CanvasJs React - Cannot assign to read only property 'exports' of object
- Getting error message "li: 'key' is not a prop"
- Input value resets when input is cleared
- Apply css class to specific element depending on state
- Can I use react router Link with CardActionArea?
- How to import a file name according to a selected option value - React
- How can i protect routes in my reactjs project?
- upload image from react to a nodejs express API
- Onclick Event formatting in React App Error
- React JS and TypeError
- Put image as an object into state variable and pass it as a props
- Getting error Cannot read property 'setState' of undefined
- How can I detect when video finished playing react?
- How to define prop validation rule for an object of objects in React?
- Mocking @material-ui/pickers in Jest
- remove active state from react component
- Loosing Focus While Typing On Custom Input Field React-Final-Form-Arrays
- communicating with a functional component outside of react
- How do I insert an HTML Script embed into React?
- Chakra ui - color mode inside extendTheme
- useContext is not displaying the updated state (when data is retrieved from firebase in useEffect hook in global file) in child component
- React onclick handler for checkbox group