I have that code, I'm not getting filter. I want to filter all that have the letter “a” but it looks like the SetState is not working. I can't find the error, someone could help me?
it looks like it's the setstate that not working. And where is "a" it will be a value of input.
I go after trying to make a search function that renders the name of the people that is matched in a search text input.
class Pagination extends React.Component {
constructor() {
super();
this.state = {
elementsPerPage:3,
currentPage:0,
peoples:[
{id:0, name:"aaa"},
{id:1, name:"bb"},
{id:2, name:"aa"},
{id:3, name:"cc"},
{id:4, name:"dada"},
{id:5, name:"Daddi"},
{id:6, name:"Dwe"},
{id:7, name:"ta"},
{id:8, name:"lala"},
{id:9, name:"lele"},
{id:10, name:"f"},
{id:11, name:"a"}],
input: "",
filtered: [],
};
this.nextPage = this.nextPage.bind(this);
this.previousPage = this.previousPage.bind(this);
this.filterNames = this.filterNames.bind(this);
this.getValueInput = this.getValueInput.bind(this);
}
getValueInput (value) {
this.setState({ input: value.target.value });
}
filterNames (){
const {peoples, filtered} = this.state;
console.log(this.state.filtered)
this.filtered = this.state.filtered.filter(item => item.includes('a'))
this.setState({filtered: this.filtered })
}
elementsOnScreen () {
const {elementsPerPage, currentPage, peoples} = this.state;
const namesInFiltered = this.state.filtered = peoples.map(item => item.name)
return namesInFiltered.map((nome) => <li>{nome}</li>)
.slice(currentPage*elementsPerPage, currentPage*elementsPerPage + elementsPerPage)
}
nextPage () {
const {elementsPerPage, currentPage, peoples} = this.state;
if((currentPage+1) * elementsPerPage < peoples.length){
this.setState({ currentPage: this.state.currentPage + 1 });
console.log(this.state.currentPage)
}
}
previousPage () {
const { currentPage } = this.state;
if(currentPage - 1 >= 0){
this.setState({ currentPage: this.state.currentPage - 1 });
}
}
render() {
return (
<div>
<input type="text" onChange={ this.getValueInput }></input>
<button className='search' onClick={this.filterNames}> Search </button>
<button onClick={this.previousPage}> Previous </button>
<button onClick={this.nextPage}> Next </button>
<ul>Names: {this.elementsOnScreen()}</ul>
<h3>Current Page: {this.state.currentPage}</h3>
</div>
);
}
}
ReactDOM.render(
<Pagination/>,
document.getElementById('root')
)
<div id="root"></div>