Im creating an invoice generator where the user can add an item, its price, and the quantity. I want to access the user inputs as a state from a child functional component (TableItems.js) into a parent functional component (TableSheet.js) to be able to save the user inputs into a database preferably firestore. I'm having a problem accessing the user input value from the child component to the parent component. I have been struggling with this bug for days, i really hope you guys could help me.
This is the Child component
import React, {useState, useEffect} from 'react'
function TableItems({index, tableItem }) {
const [price, setPrice] = useState(0);
const [qty, setQty] = useState(0);
const [total, setTotal] = useState([]);
useEffect(() => {
//arithmetically add price and qty values
const x = Number(price) * Number(qty)
setTotal(x)
return () => {
//clean up function will be here
};
}, [price, qty, total ]);
return (
<>
<tr>
<td><input type='text' required/></td>
<td><input type='number' value={price} onChange={(e) => setPrice(e.target.value)}/></td>
<td><input type='number' value={qty} onChange={(e) => setQty(e.target.value)}/></td>
<td>{total}</td>
</tr>
</>
)
}
export default TableItems
This is the Parent component
import React, { useState } from 'react'
import TableItems from './TableItems'
function TableSheet() {
const [tableItem, setTableItem] = useState([1]);
//adding a new table cell (table row)
const addCell = () => {
setTableItem((t) => [...t, t + 1])
}
return (
<div>
<table>
<thead>
<th>Item Description</th>
<th>Price</th>
<th>Qty.</th>
<th>Total</th>
</thead>
{
tableItem.map((tableItem, index, setItem) => {
return <TableItems key={index} tableItem={tableItem} setItem={setItem} addCell={addCell}/>
})
}
</table>
<button onClick={addCell}>+</button>
</div>
)
}
export default TableSheet
You tableItem state should contains item objects (quantity and price)
TableItems
function TableItems({ index, tableItem, onChangeItem }) {
return (
<>
<tr>
<td>
<input type="text" required />
</td>
<td>
<input
type="number"
value={tableItem.price}
onChange={(e) => onChangeItem(index, "price", e.target.value)}
/>
</td>
<td>
<input
type="number"
value={tableItem.quantity}
onChange={(e) => onChangeItem(index, "quantity", e.target.value)}
/>
</td>
<td>{Number(tableItem.price) * Number(tableItem.quantity)}</td>
</tr>
</>
);
}
TableSheet
function TableSheet() {
const [tableItem, setTableItem] = useState([
{
price: 0,
quantity: 0
}
]);
const onChangeItem = (index, type, value) => {
const newTable = tableItem.map((item, idx) => {
if (idx === index)
return {
...item,
[type]: value
};
return item;
});
setTableItem(newTable);
};
const addCell = () => {
setTableItem((t) => [
...t,
{
price: 0,
quantity: 0
}
]);
};
const totalPrice = tableItem.reduce((acc, cur) => {
acc += Number(cur.price) * Number(cur.quantity);
return acc;
}, 0);
return (
<div>
<table>
<thead>
<th>Item Description</th>
<th>Price</th>
<th>Qty.</th>
<th>Total</th>
</thead>
{tableItem.map((tableItem, index) => {
return (
<TableItems
key={index}
index={index}
tableItem={tableItem}
onChangeItem={onChangeItem}
/>
);
})}
</table>
<button onClick={addCell}>+</button>
<div>Total: {totalPrice}</div>
</div>
);
}
you can check in my codesandbox. Hope it help!
Related
I'm trying to implement a delete operation on table rows. but it keeps on throwing errors. So I need some help to figure this out.
I don't know to how to set id that can be auto incremented so I gave Date.now().
now what I want is to delete the row that i perform the delete operation on.
I'm new to react so sorry for the bad code. thank you in advance.
heres my code
import React from "react";
import { CirclesWithBar } from "react-loader-spinner";
import { useState } from "react";
import Table from "./Table";
function Main() {
// *****INITIALIZING*****
const [tableData, setTableData] = useState([])
const [formInputData, setformInputData] = useState(
{
id: Date.now(),
Name: '',
email: '',
}
);
const [loading, setloading] = useState(false);
// const deleteTableRows = (index)=>{
// const rows = [...rowsData];
// rows.splice(index, 1);
// setTableData(rows);
// }
// **********DECLARING FUNCTIONS*********
const handleChange = (evnt) => {
const newInput = (data) => ({ ...data, id: Date.now(), [evnt.target.name]: evnt.target.value })
setformInputData(newInput)
}
const handleSubmit = (evnt) => {
evnt.preventDefault();
setloading(true)
const checkEmptyInput = !Object.values(formInputData).every(res => res === "")
if (checkEmptyInput) {
const newData = (data) => ([...data, formInputData])
setTableData(newData);
const emptyInput = { id: '', Name: '', email: '' }
setformInputData(emptyInput)
}
setTimeout(() => {
setloading(false)
}, 1000)
}
const singleDelete = (event) => {
event.preventDefault();
setloading(true)
const handleDelete = (id) => {
const newArr = [...tableData];
console.log(tableData);
const index = setTableData.findIndex((data) => data.name(id) === id);
console.log(index);
newArr.splice(index, 1);
setTableData(newArr);
}
setTimeout(() => {
setloading(false)
}, 1000)
}
// ************RETURNING VALUES************
return (
<div className="container">
<div className="row">
<div className="col-sm-8">
<div className="col">
<input type="text" onChange={handleChange} value={formInputData.Name} name="Name" className="form-control" placeholder="Name" />
</div>
<div className="col">
<input type="email" onChange={handleChange} value={formInputData.email} name="email" className="form-control" placeholder="Email Address" />
</div>
<div className="col">
<input type="submit" onClick={handleSubmit} className="btn btn-success" />
{
loading ?
<CirclesWithBar
height="75"
width="100"
color="#002B5B"
wrapperStyle={{}}
wrapperClass=""
visible={true}
alignSelf='center'
outerCircleColor=""
innerCircleColor=""
barColor=""
ariaLabel='circles-with-bar-loading' loading={loading} size={50} />
:
<div>
{
<table className="table" id='table'>
<thead>
<tr>
<th>S.N</th>
<th>ID</th>
<th>Full Name</th>
<th>Email Address</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{
tableData.map((data, index) => {
return (
<tr>
<td>{index + 1}</td>
<td>{data.id}</td>
<td>{data.Name}</td>
<td>{data.email}</td>
<td><button value={data.id} onClick={() => singleDelete(data.id)} className="btn btn-danger">Delete</button></td>
</tr>
)
})
}
</tbody>
</table>
}
</div>
}
</div>
</div>
</div>
</div>
);
}
export default Main;
First, the error happens because you don't pass the click event parameter to the function.
It should be like that.
(e) => singleDelete(e, data.id)
Second, You can just use filter method to delete the item by add a condition any element that doesn't have this id.
const singleDelete = (event, id) => {
event.preventDefault();
setloading(true);
setTableData((prev) => prev.filter((i) => i.id !== id));
setTimeout(() => {
setloading(false);
}, 1000);
};
This is a full example of code.
import React from "react";
import { CirclesWithBar } from "react-loader-spinner";
import { useState } from "react";
function Main() {
// *****INITIALIZING*****
const [tableData, setTableData] = useState([]);
const [formInputData, setformInputData] = useState({
id: Date.now(),
Name: "",
email: ""
});
const [loading, setloading] = useState(false);
// const deleteTableRows = (index)=>{
// const rows = [...rowsData];
// rows.splice(index, 1);
// setTableData(rows);
// }
// **********DECLARING FUNCTIONS*********
const handleChange = (evnt) => {
const newInput = (data) => ({
...data,
id: Date.now(),
[evnt.target.name]: evnt.target.value
});
setformInputData(newInput);
};
const handleSubmit = (evnt) => {
evnt.preventDefault();
setloading(true);
const checkEmptyInput = !Object.values(formInputData).every(
(res) => res === ""
);
if (checkEmptyInput) {
const newData = (data) => [...data, formInputData];
setTableData(newData);
const emptyInput = { id: "", Name: "", email: "" };
setformInputData(emptyInput);
}
setTimeout(() => {
setloading(false);
}, 1000);
};
const singleDelete = (event, id) => {
event.preventDefault();
setloading(true);
setTableData((prev) => prev.filter((i) => i.id !== id));
setTimeout(() => {
setloading(false);
}, 1000);
};
// ************RETURNING VALUES************
return (
<div className="container">
<div className="row">
<div className="col-sm-8">
<div className="col">
<input
type="text"
onChange={handleChange}
value={formInputData.Name}
name="Name"
className="form-control"
placeholder="Name"
/>
</div>
<div className="col">
<input
type="email"
onChange={handleChange}
value={formInputData.email}
name="email"
className="form-control"
placeholder="Email Address"
/>
</div>
<div className="col">
<input
type="submit"
onClick={handleSubmit}
className="btn btn-success"
/>
{loading ? (
<CirclesWithBar
height="75"
width="100"
color="#002B5B"
wrapperStyle={{}}
wrapperClass=""
visible={true}
alignSelf="center"
outerCircleColor=""
innerCircleColor=""
barColor=""
ariaLabel="circles-with-bar-loading"
loading={loading}
size={50}
/>
) : (
<div>
{
<table className="table" id="table">
<thead>
<tr>
<th>S.N</th>
<th>ID</th>
<th>Full Name</th>
<th>Email Address</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{tableData.map((data, index) => {
return (
<tr>
<td>{index + 1}</td>
<td>{data.id}</td>
<td>{data.Name}</td>
<td>{data.email}</td>
<td>
<button
value={data.id}
onClick={(e) => singleDelete(e, data.id)}
className="btn btn-danger"
>
Delete
</button>
</td>
</tr>
);
})}
</tbody>
</table>
}
</div>
)}
</div>
</div>
</div>
</div>
);
}
export default Main;
This is working example with codesandbox.
Just modify your singleDelete function in this way -
const singleDelete = (id) => {
setloading(true);
const newTableData = tableData.filter(item => item.id !== id );
setTableData(newTableData)
setTimeout(() => {
setloading(false)
}, 1000)
}
i'm new to reactjs and i'm trying to make a table that shows the information from a array of objects and have a button of delete and an input to search among the users. The delete button is working correctly when i'm not searching anything, but when i'm searching it doesn't delete the corretly row, and deletes only the first one. I see that it is because the arrays that show the table are different with and without the search being used but I don't know how to make it work.
this is the component of the table:
import { formatDate } from "../../utils/formatDate";
import "./table.css";
import { useState } from "react";
function Table(props) {
const { headerData, bodyData, type, removeItem} = props;
const isUser = type === "user";
const buildTableItems = () => {
return bodyData.map((item, index) => (
<tr className="data-tr">
<td>{item.name}</td>
<td>{item.email}</td>
<td>{item.occupation}</td>
<td>{formatDate(item.birthday)}</td>
<td>
<button className="delete-button" onClick={() => removeItem(index)}>
Delete
</button>
</td>
</tr>
));
};
return (
<div className="user-data">
<table className="user-table">
<thead>
<tr className="data-th">
{headerData.map((headerTable) => (
<th >{headerTable}</th>
))}
</tr>
</thead>
<tbody>{buildTableItems()}</tbody>
</table>
</div>
);
}
export default Table;
Here the component of the search bar:
import "./searchBar.css"
function SearchBar({ searchedData, onSearch }) {
return (
<div className="search-bar">
<label>Search</label>
<input type="text" placeholder="Search User" value={searchedData} onChange={e => onSearch(e.target.value)} />
</div>
);
}
export default SearchBar;
and here is the home:
import "./Home.css";
import React, { useEffect, useState } from "react";
import Header from "../components/Header/Header";
import Table from "../components/Table/Table";
import AddData from "../components/AddData/AddData";
import SearchBar from "../components/SearchBar/SearchBar";
import { userArr } from "../mock/users";
const Home = () => {
const headerUser = ["Name", "Email", "Occupation", "Birthday"];
const [newUserArr, setNewUserArr] = useState(userArr);
const [searchedItem, setSearchedItem] = useState("");
const searchedArray = newUserArr.filter((item) => {
if (item.name.toLowerCase().includes(searchedItem.toLowerCase())) {
return true;
}
});
function onSearch(e) {
setSearchedItem(e);
}
const addDataToArr = (form) => {
setNewUserArr([...newUserArr, form]);
};
const deleteData = (indexUserArr) => {
let restOfDataArray = newUserArr.filter(
(element, ind) => ind !== indexUserArr
);
setNewUserArr(restOfDataArray);
};
return (
<>
<Header />
<SearchBar searchedData={searchedItem} onSearch={onSearch} />
<Table
type="user"
headerData={headerUser}
bodyData={newUserArr}
removeItem={(index) => deleteData(index)}
/>
<AddData saveData={(val) => addDataToArr(val)} />
</>
);
};
export default Home;
thank you
If you have ID in your user data then use that instead of index or create id keywords using concatenate with your values here is examples.
import { formatDate } from "../../utils/formatDate";
import "./table.css";
import { useState } from "react";
function Table(props) {
const { headerData, bodyData, type, removeItem} = props;
const isUser = type === "user";
const buildTableItems = () => {
return bodyData.map((item, index) => (
<tr className="data-tr">
<td>{item.name}</td>
<td>{item.email}</td>
<td>{item.occupation}</td>
<td>{formatDate(item.birthday)}</td>
<td>
<button className="delete-button" onClick={() => removeItem(`${item.name}${item.email}${item.occupation}`)}>
Delete
</button>
</td>
</tr>
));
};
return (
<div className="user-data">
<table className="user-table">
<thead>
<tr className="data-th">
{headerData.map((headerTable) => (
<th >{headerTable}</th>
))}
</tr>
</thead>
<tbody>{buildTableItems()}</tbody>
</table>
</div>
);
}
export default Table;
And here is your delete method ${item.name}${item.email}${index}
const deleteData = (data) => {
let restOfDataArray = newUserArr.filter(
(element, ind) => `${element.name}${element.email}${element.occupation}` !== data
);
setNewUserArr(restOfDataArray);
};
This will fixed your problem. If this doesn't work then you need to use ID to resolve this problem. There is a possibility that ${item.name}${item.email}${item.occupation} can be duplicates.
Never use index ever for deleting or any other operations. Use always ID.
I'm doing this React.js project and I have to use POST method. I've managed to make the item appear in the the console and in the json file, but it's not showing in my table. I assume It has to do something with the useEffect hook, but since I'm very new to all of this, I don't know how to implement it correctly.
Table
import React, { useState, useEffect } from "react";
import axios from "axios";
const Table = () => {
//FETCH API
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
const fetchPosts = async () => {
setLoading(true);
const res = await axios.get("http://localhost:3000/movies");
setPosts(res.data);
setLoading(false);
};
fetchPosts();
}, []);
//SORTING
const [order, setOrder] = useState("ascending");
const sorting = (s) => {
if (order === "ascending") {
const sorted = [...posts].sort((a, b) =>
a[s].toLowerCase() > b[s].toLowerCase() ? 1 : -1
);
setPosts(sorted);
setOrder("descending");
}
if (order === "descending") {
const sorted = [...posts].sort((a, b) =>
a[s].toLowerCase() < b[s].toLowerCase() ? 1 : -1
);
setPosts(sorted);
setOrder("ascending");
}
};
//TABLE
return (
<div className="container">
<table className="table table-bordered table-striped">
<thead>
<tr>
<th className="click" onClick={() => sorting("name")}>
Name
</th>
<th>Genre</th>
<th>Rating</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{posts.map((post) => (
<tr key={post}>
<td>{post.name}</td>
<td>{post.genre}</td>
<td>{post.rating}</td>
<td>
{<button className="btn btn-outline-success">delete</button>}
{<button className="btn btn-outline-warning">edit</button>}
</td>
</tr>
))}
</tbody>
</table>
</div>
);
};
export default Table;
AddForm
import React from "react";
import { useState } from "react";
function AddForm() {
const [name, setName] = useState("");
const [genre, setGenre] = useState("");
const [rating, setRating] = useState("");
const handleSubmit = (e) => {
fetch("http://localhost:3000/movies", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: name,
genre: genre,
rating: rating,
}),
})
.then((response) => response.json())
.then((response) => {
console.log(response);
});
e.preventDefault();
};
return (
<div className="text-center">
<h2>Add a New movie</h2>
<form onSubmit={handleSubmit}>
<label>Name:</label>
<input
name="name"
type="text"
required="required"
onChange={(e) => setName(e.target.value)}
/>
<label>Genre:</label>
<input
name="genre"
type="text"
required="required"
onChange={(e) => setGenre(e.target.value)}
/>
<label>Rating:</label>
<input
name="rating"
type="text"
required="required"
onChange={(e) => setRating(e.target.value)}
/>
<button type="submit">Add</button>
</form>
</div>
);
}
export default AddForm;
This is my librarylist component in which i pass deletehandler function to delete the row from library management. I don't know which part of the code is causing the problem. Any helps/suggestions are welcome.
LibraryBookList.js
const LibraryBookList = (props) => {
const[database, setDatabase]=useState()
const deleteHandler = (bookdataId) => {
const newDatabase=[...database];
const index= database.findIndex((bookdata)=>bookdata.id===bookdataId)
newDatabase.splice(index,1)
setDatabase(newDatabase);
} ;
return (
<ul className={classes.list}>
{props.database.map((bookdata) =>
(<LibraryBook
key={bookdata.key}
id={bookdata.id}
bookname={bookdata.bookName}
author={bookdata.author}
publisher={bookdata.publisher}
pages={bookdata.pages}
serialno={bookdata.serialNo}
onSelect={deleteHandler}
/>
))}
</ul>
)};
here i pass deletehandler via props
LibraryBook.js
const LibraryBook = (props) => {
return (
<li>
<table className={classes.table}>
<tbody>
<tr className={classes.table_row}>
<td className={classes.row_data}>{props.serialno}</td>
<td className={classes.row_data}>{props.pages}</td>
<td className={classes.row_data}>{props.bookname}</td>
<td className={classes.row_data}>{props.author}</td>
<td className={classes.row_data}>{props.publisher}</td>
<td>
<button className={classes.delete_btn} onClick={(props.onSelect(props.id))}>
Delete
</button>
</td>
</tr>
</tbody>
</table>
</li>
export default LibraryBookList;
**BookData.js **
const BookData = (props) => {
const [isLoading, setIsLoading] = useState(true);
const [loadedLibrarydata, setLoadedLibrarydata] = useState();
useEffect(() => {
setIsLoading(true);
fetch(
"https://librarymanagement-70ab2-default-rtdb.firebaseio.com/database.json"
)
.then((response) => {
// console.log('response',response.json())
return response.json();
})
.then((data) => {
const database = [];
console.log("data", data);
for (const key in data) {
const bookdata = {
id: key,
...data[key],
};
database.push(bookdata);
}
setIsLoading(false);
setLoadedLibrarydata(database);
});
}, []);
if (isLoading) {
return (
<section>
<p>Loading.....</p>
</section>
);
}
return (
<section>
<h1>Book Data Base</h1>
<table className={classes.table}>
<thead>
<tr className={classes.table_row}>
<th className={classes.row_heading}>Serial No</th>
<th className={classes.row_heading}>Pages</th>
<th className={classes.row_heading}>Book Name</th>
<th className={classes.row_heading}>Author</th>
<th className={classes.row_heading}>Publisher</th>
</tr>
</thead>
</table>
{loadedLibrarydata && loadedLibrarydata.length && (
<LibraryBooklist database={loadedLibrarydata} />
)}
</section>
);
};
export default BookData;
NewDataBase.js
const NewDataBase = () => {
const history=useHistory();
const addDataHandler = (bookData) => {
console.log('bookData',bookData);
fetch(
"https://librarymanagement-70ab2-default-rtdb.firebaseio.com/database.json",
{
method: "POST",
body: JSON.stringify(bookData),
headers: {
"Content-type": "application/json",
},
}
).then(()=>{
history.replace('/')
})
};
return (
<section>
<DataBaseForm onAddNewData={addDataHandler} />
</section>
);
};
export default NewDataBase;
The code has a few issues: 1) props.onSelect(props.id) inside onClick. Instead you should give a referance to that function. 2) You didn't have anything in database state before you click delete button. That is why ... spread operator didn't work 3) You are displaying props.database instead of database state. That is way the changes didn't show up even after you deleted a bookdata. I also fixed some small issues. Now it is working perfectly:
// !! you can put all the code into one file and run for testing.
// !! I removed stylings as I didn't have the source
import {useState, useEffect} from 'react'
const LibraryBooklist = (props) => {
const[database, setDatabase]=useState(props.database)
const deleteHandler = (bookdataId) => {
const newDatabase=database.filter((bookdata)=>bookdata.id!==bookdataId);
setDatabase(newDatabase);
}
return (
<ul>
{database.map((bookdata) =>
<LibraryBook
key={bookdata.id}
id={bookdata.id}
bookname={bookdata.bookName}
author={bookdata.author}
publisher={bookdata.publisher}
pages={bookdata.pages}
serialno={bookdata.serialNo}
onSelect={deleteHandler}
/>
)}
</ul>
)};
const LibraryBook = (props) => {
const {id, onSelect} = props
return (
<li>
<table>
<tbody>
<tr>
<td>{props.serialno}</td>
<td>{props.pages}</td>
<td>{props.bookname}</td>
<td>{props.author}</td>
<td>{props.publisher}</td>
<td>
<button onClick={() => onSelect(id)}>
Delete
</button>
</td>
</tr>
</tbody>
</table>
</li>
)}
const BookData = (props) => {
const [isLoading, setIsLoading] = useState(true);
const [loadedLibrarydata, setLoadedLibrarydata] = useState();
useEffect(() => {
setIsLoading(true);
fetch(
"https://librarymanagement-70ab2-default-rtdb.firebaseio.com/database.json"
)
.then((response) => {
// console.log('response',response.json())
return response.json();
})
.then((data) => {
const database = [];
for (const key in data) {
const bookdata = {
id: key,
...data[key],
};
database.push(bookdata);
}
setIsLoading(false);
setLoadedLibrarydata(database);
});
}, []);
if (isLoading) {
return (
<section>
<p>Loading.....</p>
</section>
);
}
return (
<section>
<h1>Book Data Base</h1>
<table>
<thead>
<tr>
<th>Serial No</th>
<th>Pages</th>
<th>Book Name</th>
<th>Author</th>
<th>Publisher</th>
</tr>
</thead>
</table>
{loadedLibrarydata && loadedLibrarydata.length && (
<LibraryBooklist database={loadedLibrarydata} />
)}
</section>
);
};
export default BookData;
I'm trying to make a table with api data searchable. I'm on my way, but unsure on how to proceed further.
Code looks like this:
const [searchTerm, setSearchTerm] = useState("");
const [searchResults, setSearchResults] = useState([]);
const handleChange = event => {
setSearchTerm(event.target.value);
};
useEffect(() => {
const results = apiData.filter(person =>
person.toLowerCase().includes(searchTerm)
);
setSearchResults(results);
}, [searchTerm]);
const renderPerson = (contact, index) => {
return (
<tr key={index}>
<td>{contact.ID}</td>
<td>{contact.Info.Name}</td>
<td>{contact.InfoID}</td>
<td>{contact.Info.DefaultEmail.EmailAddress}</td>
<td>{contact.Info.DefaultPhone.Number}</td>
<td>{contact.Info.InvoiceAddress.AddressLine1}</td>
</tr>
)
}
return (
<Fragment>
<input type="text" value={searchTerm} onChange={handleChange} placeholder="Søk.."></input>
<table id="myTable">
<thead>
<tr className="header">
<th>ID</th>
<th>Navn</th>
<th>Info Id</th>
<th>E-post</th>
<th>Telefon</th>
<th>Adresse</th>
</tr>
</thead>
<tbody>
{apiData.map(renderPerson)}
</tbody>
</table>
</Fragment>
)
https://dev.to/asimdahall/simple-search-form-in-react-using-hooks-42pg
I've followed this guide, but since I have the renderPerson function, I'm a bit unsure on how to handle this.
Question: Is there any way to get this working, or am I approaching it the wrong way? I'm aware that I need to put searchResult in the tbody somehow, but then the table won't be populated.
Any help is much appreciated
Edit: displaying code for getting apiData:
useEffect(() => {
getContacts()
}, [])
const getContacts = () => {
$.ajax({
url: `http://localhost:5000/getContacts`,
type: "POST",
data: ajaxObj,
success: (data) => {
let response = JSON.parse(data)
setApiData(response)
setLoading(false)
},
error: () => {
console.log("noe feilet?");
}
});
}
console.log(apiData)
Data looks like this:
data
Change apiData to searchResults on render
<tbody>
{searchResults.map(renderPerson)}
</tbody>
Change your filter way result (Updated)
const results = apiData.filter(person =>
person.Info.Name.toLowerCase().includes(searchTerm)
);
....
const renderPerson = (item, index) => {
return (
<tr key={index}>
<td>{item.ID}</td>
<td>{item.Info.Name}</td>
<td>{item.InfoID}</td>
<td>{item.Info.DefaultEmail.EmailAddress}</td>
<td>{item.Info.DefaultPhone.Number}</td>
<td>{item.Info.InvoiceAddress.AddressLine1}</td>
</tr>
)
}
Try this
export default function () {
const [searchTerm, setSearchTerm] = useState("");
const [searchResults, setSearchResults] = useState([]);
const apiData=[
{
ID:'1222',
Info:{
ID:'1222',
EmailAddress:'test#test.com',
Number:'2222222222',
AddressLine1:'test'
}
},
{
ID:'2333',
Info:{
ID:'2333',
EmailAddress:'test2#test.com',
Number:'1111111111',
AddressLine1:'test2'
}
}
]
const handleChange = event => {
setSearchTerm(event.target.value);
if(event.target.value){
const results = apiData.filter(person =>
person.ID.toLowerCase().includes(event.target.value)
);
setSearchResults(results);
}else{
setSearchResults([]);
}
};
const renderPerson = (contact, index) => {
return (
<tr key={index}>
<td>{contact.ID}</td>
<td>{contact.Info.Name}</td>
<td>{contact.Info.ID}</td>
<td>{contact.Info.EmailAddress}</td>
<td>{contact.Info.Number}</td>
<td>{contact.Info.AddressLine1}</td>
</tr>
)
}
return (
<Fragment>
<input type="text" value={searchTerm} onChange={handleChange} placeholder="Søk.."></input>
<table id="myTable">
<thead>
<tr className="header">
<th>ID</th>
<th>Navn</th>
<th>Info Id</th>
<th>E-post</th>
<th>Telefon</th>
<th>Adresse</th>
</tr>
</thead>
<tbody>
{searchResults.map(renderPerson)}
</tbody>
</table>
</Fragment>
)
}