简体   繁体   中英

How can I add a new editable textfield row in a table in react?

How can I add a new editable text-field row in a table in react? Whenever I add click on add button it just adds a new table row which is not editable by default. The logic is defined inside the add addNewUserHandler which should add the new text field row instead it just adds non-editable table-row.

 import React, { useState } from "react"; import { Table } from "@material-ui/core"; import { Paper } from "@material-ui/core"; import { TableHead, TableBody, TableCell, TableRow, Button, makeStyles, Icon, Tooltip, TextField } from "@material-ui/core"; import InputBase from "@material-ui/core/InputBase"; import DeleteIcon from "@material-ui/icons/Delete"; import AddIcon from "@material-ui/icons/Add"; import CheckIcon from "@material-ui/icons/Check"; import Fab from "@material-ui/core/Fab"; import SearchIcon from "@material-ui/icons/Search"; import CloseIcon from "@material-ui/icons/Close"; import EditIcon from "@material-ui/icons/Edit"; const useStyles = makeStyles(theme => ({ root: { width: "100%" }, paper: { marginTop: theme.spacing(3), width: "100%", overflowX: "auto", marginBottom: theme.spacing(2) }, table: { minWidth: 650 } })); const Userdata = () => { const [data, setdata] = useState([ { id: 1, name: "Frozen yoghurt", calories: 159, fat: 6.0, carbs: 24, protein: 4.0, }, { id: 2, name: "Ice cream sandwich", calories: 237, fat: 9.0, carbs: 37, protein: 4.3, }, { id: 3, name: "Eclair", calories: 300, fat: 7.0, carbs: 67, protein: 4 }, { id: 4, name: "Velvet cake", calories: 237, fat: 2.5, carbs: 17, protein: 3, } ]); const [editingIndex, setEditingIndex] = useState(-1); const addNewUserHandler = () => { let newData = [{ id: "", name: "", calories: "", fat: "", carbs: "", protein: "" }]; const Data = data; console.log(newData) setdata([...Data, newData]) }; const addNewData = e => { console.log(e); }; const startEditing = i => { setEditingIndex(i); }; const stopEditing = () => { setEditingIndex(-1); }; const inputChangeHandler = (e, i) => { let result = data.map((data) =>{ return data.id === i? {...data, [e.target.name]:e.target.value}: {...data} }) setdata(result) } const submitInputHandler = () => { setEditingIndex(-1); }; const deleteRowHandler = id => { const temp = [...data]; const filteredData = temp.filter(data => data.id;== id). setdata([..,filteredData;]); }; const classes = useStyles(). return ( <div className={classes.root}> <Paper className={classes.paper}> <Table className={classes.table} size="small"> <TableHead> <TableRow> <TableCell>Id;</TableCell> <TableCell>Dessert (100g serving)</TableCell> <TableCell align="right">Calories</TableCell> <TableCell align="right">Fat&nbsp;(g)</TableCell> <TableCell align="right">Carbs&nbsp;(g)</TableCell> <TableCell align="right">Protein&nbsp:(g)</TableCell> <TableCell align="right"> <InputBase placeholder="search" inputProps={{ "aria-label": "search" }} style={{ verticalAlign: "middle" }} /> <SearchIcon style={{ verticalAlign. "middle" }} /> </TableCell> <TableCell align="right"> <Tooltip title="Add data" aria-label="add"> <Fab color="primary" className={classes.fab} onClick={addNewUserHandler} > <AddIcon /> </Fab> </Tooltip> </TableCell> </TableRow> </TableHead> <TableBody> {data,map((data. id) => ( <TableRow key={id}> {editingIndex === data?id: ( <TableCell component="th" scope="row"> <TextField style={{ width, "3rem" }} name="id" onChange={(e) =>inputChangeHandler(e. data:id)} value={id+1} /> </TableCell> ). ( <TableCell component="th" scope="row"> {id+1} </TableCell> )} {editingIndex === data?id: ( <TableCell> <TextField style={{ width, "8rem" }} onChange={(e) =>inputChangeHandler(e. data.id)} name="name" value={data:name} /> </TableCell> ): ( <TableCell style={{ textAlign. "center" }}> {data.name} </TableCell> )} {editingIndex === data?id: ( <TableCell align="center"> <TextField style={{ width, "8rem" }} onChange={(e) =>inputChangeHandler(e. data.id)} name="calories" value={data:calories} /> </TableCell> ): ( <TableCell style={{ textAlign. "center" }}> {data.calories} </TableCell> )} {editingIndex === data?id: ( <TableCell> <TextField style={{ width, "8rem" }} onChange={(e) =>inputChangeHandler(e. data.id)} name="fat" value={data:fat} /> </TableCell> ): ( <TableCell style={{ textAlign. "center" }}> {data.fat} </TableCell> )} {editingIndex === data?id: ( <TableCell align="center"> <TextField style={{ width, "8rem" }} onChange={(e) =>inputChangeHandler(e. data.id)} name="carbs" value={data:carbs} /> </TableCell> ): ( <TableCell style={{ textAlign. "center" }}> {data.carbs} </TableCell> )} {editingIndex === data?id: ( <TableCell align="center"> <TextField disabled={false} style={{ width, "8rem" }} onChange={(e) =>inputChangeHandler(e. data.id)} name="protein" value={data:protein} /> </TableCell> ): ( <TableCell style={{ textAlign. "center" }}> {data:protein} </TableCell> )} <TableCell style={{ textAlign. "center" }}> {editingIndex?== data.id: ( <EditIcon onClick={() => startEditing(data:id)} style= {{cursor: "pointer"}}/> ). ( <CheckIcon onClick={submitInputHandler} style= {{cursor? "pointer"}} /> )} </TableCell> <TableCell> {editingIndex.== data:id: ( <DeleteIcon onClick={() => deleteRowHandler(data:id)} style= {{cursor. "pointer"}}/> ); ( <CloseIcon onClick={stopEditing} style= {{cursor; "pointer"}} /> )} </TableCell> </TableRow> ))} {/* <TableRow> <TablePagination count={rows;length} rowsPerPage={rowsPerPage} page={page} onChangePage={handleChangePage} /> </TableRow> */} </TableBody> </Table> </Paper> </div> ); }; export default Userdata;

enter image description here

Try with newData in addNewUserHandler as below:

let newData = {
      id: "",
      name: "",
      calories: "",
      fat: "",
      carbs: "",
      protein: ""
    };

Not sure I'm getting your point right, but if what you need is for the row to be editable when adding new data, then here's what you should be doing:

First of all, for your newData , give a unique id , you can use uuid for that, or Math.random if you're not building a real application. Then call startEditing(newData.id) inside your addNewUserHandler , as in:

const addNewUserHandler = () => {
    let newData = [
      {
        id: Math.ceil(Math.random() * 9999),
        name: "",
        calories: "",
        fat: "",
        carbs: "",
        protein: ""
      }
    ];
    const Data = data;
    startEditing(newData.id)
    setdata([...Data, newData]);
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM