I am studying react. I am struggling to use JavaScript prototype. What I want to do is below.
- If
searchWord
is typed, filter the array(props.rows
) to one containing the word. - If the number of elements has more than
rowsPerPage
, onlyrowsPerPage
are displayed.
However, what I typed worked reversely like this.
Slice elements in rowsPerPage
, and then filter elements containing searchWord
.
I don't know which function is needed. Please help me. Thank you in advance.
(If it is possible to write code using only prototype, I want to do.)
( I edited code to trim it.)
// reversed sequence
{(rowsPerPage > 0
? props.rows.slice(page * rowsPerPage, page * rowsPerPage rowsPerPage)
: props.rows
)
.filter((row) =>
!searchWord.length || row.name
.toString()
.includes(searchWord.toString())
)
.map((item) => (
<Hello />
))}
// what I tried
{props.rows
.filter((row) =>
!searchWord.length || row.name
.toString()
.includes(searchWord.toString())
)
?????.((?????) => (
rowsPerPage > 0
? ?????.slice(page * rowsPerPage, page * rowsPerPage rowsPerPage)
: ?????
))
.map((item) => (
<Hello />
))}
CodePudding user response:
try to move it to the variable
let filteredRows = props.rows
.filter((row) =>
!searchWord.length || row.name
.toString()
.toLowerCase()
.includes(searchWord.toString().toLowerCase())
);
if (rowsPerPage > 0) {
filteredRows = filteredRows.slice(page * rowsPerPage, page * rowsPerPage rowsPerPage)
}
return filteredRows.map(item => (
<TableRow key={item.id} hover>
<TableCell component="th" scope="row">
{item.id}
</TableCell>
<TableCell>
{item.name}
</TableCell>
</TableRow>
))
or not recommended approach
{props.rows
.filter((row) =>
!searchWord.length || row.name
.toString()
.toLowerCase()
.includes(searchWord.toString().toLowerCase())
)
.slice(...(rowsPerPage > 0 ? [page * rowsPerPage, page * rowsPerPage rowsPerPage] : []))
.map((item) => (
<TableRow key={item.id} hover>
<TableCell component="th" scope="row">
{item.id}
</TableCell>
<TableCell>
{item.name}
</TableCell>
</TableRow>
))}