Reputation: 51
I'm new to react and am working on a search feature, I have some dummy data stored in an object, I'm mapping over it and displaying it on the page. I've written the search functionality to search the list which is working great. This may be a stupid question, but I don't want the list items to be displayed on the page until text is entered into the input field, in my head I'm thinking a simple if statement would do, but I'm having a little trouble. Any guidance would be much appreciated.
const isSearched = searchTerm => item =>
item.title.toLowerCase().includes(searchTerm.toLowerCase());
const list = [
{
title: 'react',
url: 'https://reactjs.org',
author: 'Jordan Walke',
num_comments: 3,
points: 4,
objectID: 0
},
{
title: 'redux',
url: 'https://redux.js.org',
author: 'Dan Abramov',
num_comments: 5,
points: 6,
objectID: 1
},
];
class App extends Component {
constructor(props) {
super(props);
this.state = {
list: list,
searchTerm: '',
};
this.onSearchChange = this.onSearchChange.bind(this);
}
onSearchChange(event) {
this.setState({ searchTerm: event.target.value });
}
render() {
return (
<div className="App">
<form>
<input
type="text"
onChange={this.onSearchChange}
/>
</form>
{this.state.list.filter(isSearched(this.state.searchTerm)).map(item
=>
<div key={item.objectID}>
<span>
<a href={item.url}>{item.title}</a>
</span>
<span>{item.author}</span>
<span>{item.num_comments}</span>
<span>{item.points}</span>
</div>
)}
</div>
);
}
}
Upvotes: 0
Views: 344
Reputation: 51
You could wrap your filter function in a conditional rendering statement.
const { searchTerm, list } = this.state;
{searchTerm !== " " && (
list.filter(searchTerm).map(item =>
<div key={item.objectID}>
<span>
<a href={item.url}>{item.title}</a>
</span>
<span>{item.author}</span>
<span>{item.num_comments}</span>
<span>{item.points}</span>
</div>
)
)};
That way your items are only rendered when searchTerm resolves to true.
[...] in JavaScript, true && expression always evaluates to expression, and false && expression always evaluates to false.
See conditional rendering in the React's doc
Upvotes: 0
Reputation: 1001
It would be pretty simple. Basically in the render function you need to check in if your searchTerm
is not ''
then render. it would look like this:
{
this.state.searchTerm !== '' &&
this.state.list.filter(isSearched(this.state.searchTerm)).map(item =>
<div key={item.objectID}>
<span>
<a href={item.url}>{item.title}</a>
</span>
<span>{item.author}</span>
<span>{item.num_comments}</span>
<span>{item.points}</span>
</div>
)
}
Upvotes: 0