Answer the question
In order to leave comments, you need to log in
How to filter posts in React?
There is a form in which the user must enter information, this form, with each change, transfers data up the hierarchy, how to make sure that posts on the page are filtered when the form changes?
Home.jsx (The component that is higher in the hierarchy)
import React, {Component} from 'react';
import db from '../db';
import Nav from '../components/Nav';
import Header from '../components/Header';
import SearchBar from '../components/SearchBar';
import Posts from '../components/Posts';
import Footer from '../components/Footer';
export default class Home extends Component{
constructor(props){
super(props);
this.handleUserInput = this.handleUserInput.bind(this);
this.state = {
filterText: ''
};
}
handleUserInput(filterText) {
this.setState({filterText: filterText}, ()=>{console.log("State: " + this.state.filterText)});
}
render(){
return(
<div className="App">
<Nav/>
<Header/>
<SearchBar
filterText={this.state.filterText}
onUserInput={this.handleUserInput}/>
<Posts handleUserIput={this.state.filterText} data={db}/>
<Footer/>
</div>
);
}
}
import React, {Component} from 'react';
export default class SearchBar extends Component{
constructor(props){
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(){
this.props.onUserInput(
this.filterTextInput.value,
);
}
render(){
return(
<div className="searchbar">
<div id="search-box">
<input
id="term"
type="text"
placeholder="Search..."
value={this.props.filterText}
ref={(input) => this.filterTextInput = input}
onChange={this.handleChange}/>
<label className="screen-reader" htmlFor="term"><i className="fa fa-search"></i></label>
</div>
</div>
);
}
}
import React, {Component} from 'react';
import Post from './Post';
export default class Posts extends Component{
render(){
return(
<section className="s-posts">
<div className="container">
<div className="row">
{
this.props.data.map(data =>
<Post key={data.id} title={data.title} img={data.img} descr={data.descr}/>
)
}
</div>
</div>
</section>
);
}
}
Answer the question
In order to leave comments, you need to log in
The list of posts is a db, right? Well, filter it before passing it to Posts. For example, like this:
render() {
const
text = this.state.filterText,
posts = text ? db.filter(n => n.descr.includes(text)) : db;
return(
<div className="App">
<Nav/>
<Header/>
<SearchBar
filterText={this.state.filterText}
onUserInput={this.handleUserInput}
/>
<Posts handleUserIput={this.state.filterText} data={posts}/>
<Footer/>
</div>
);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question