Reputation: 33
I'm trying to add a search input to filter the data I receive from the database. Could anybody walk me through how I can go about filtering and displaying on the results that are searched. I want to search for the MeetingName that was mapped from items. Right now the app is displaying the entire list of items from the database.
Thanks.
import React, { Component } from 'react';
import { Table, Input } from 'reactstrap';
import { connect } from 'react-redux';
import { getItems, deleteItem } from "../actions/itemActions";
import PropTypes from 'prop-types';
class Directory extends Component {
componentDidMount() {
this.props.getItems();
}
onDeleteClick = (id) => {
this.props.deleteItem(id);
}
render() {
const { items } = this.props.item;
return(
<div>
<Input type="text" placeholder="search"/>
<br/>
<Table>
<thead>
<tr>
<th>Day</th><th>Time</th><th>Meeting Name</th><th>Address</th><th>City</th><th>Zip Code</th><th></th>
</tr>
</thead>
{items.map(({ _id, Day, Time, MeetingName, Address, City, Zip }) => (
<tbody key={_id}>
<tr>
<td>{Day}</td><td>{Time}</td><td>{MeetingName}</td><td>{Address}</td><td>{City}</td><td>{Zip}</td>
{/*<Button
className="remove-btn"
color="danger"
size="sm"
onClick={this.onDeleteClick.bind(this, _id)}
>
×
</Button>*/}
</tr>
</tbody>
))}
</Table>
</div>
);
}
}
Directory.propTypes = {
getItems: PropTypes.func.isRequired,
item: PropTypes.object.isRequired
}
const mapStateToProps = (state) => ({
item: state.item
})
export default connect(
mapStateToProps,
{ getItems, deleteItem }
)(Directory);
Upvotes: 1
Views: 5517
Reputation: 1847
You need to change few things in your component
Initialise state in constructor as below
this.state = { searchedValue: '' };
Add an onChange event listener on input
<input type="text" placeholder="search" onChange={this.onSearch} value={this.state.searchedValue} />
Change the state with typed value when onSearch
function is called
onSearch = (event) => {
this.setState({ searchedValue: event.target.value });
}
Filter the items
list with the searchedValue in render
function
const filteredItems = items.filter((item) => item.meetingName.includes(this.state.searchedValue));
Use the filteredItems
array to create multiple tr
As stated in the comment on your post, react-data-grid is a nice option but you can choose what fits best for your application
Upvotes: 2