I'm a newbie in React. I'm creating a little app that has users and I need to create a searchbar that will look for users if I type two or three lettters of users name. But obviously I stuck. So any help will be nice. Thanks in advance
import React, { Component } from 'react'
class FilterForm extends Component {
state = {
query: '',
user: [],
searchString:[]
}
handleInputChange = (e) => {
this.setState ({
query:e.target.value
} ,()=>{
this.filterArray();
})
}
getData = () => {
fetch(`http.//localhost:3000/login`)
.then(response => response.json())
.then(responseData => {
//console.log(responseData)
this.setState ({
user:responseData,
searchString: responseData
})
})
}
filterArray = () => {
let searchString = this.state.query;
let responseData = this.state.user;
if(searchString.length > 0){
//console.log(responseData[i].first_name)
searchString = responseData.filter(searchString);
this.setState({ responseData })
}
}
componentWillMount() {
this.getData();
}
render() {
return(
<div className="searchform">
<form>
<input
type="text"
id="filter"
placeholder="Search for user..."
onChange={this.handleInputChange}/>
</form>
<div>{this.state.searchString.map(i => <p>{i.first_name}</p>)}
</div>
</div>
)
}
}
export default FilterForm
And this is my App.js
import React from 'react';
import PeopleList from "./components/PeopleList"
import FilterForm from "./components/FilterForm"
//import { search } from "./Utils"
//import UserData from "./components/UserData";
//import SearchBox from "./components/SearchBox"
import './App.css';
class App extends React.Component {
render() {
return (
<React.Fragment>
<div>
<FilterForm />
<PeopleList />
</div>
</React.Fragment>
);
}
}
export default App
And when I start typing something in searchbar I get an error:
I edit your post and did some indentation, and to your question, your problem is in fillterArray, this is not how you use filter method and you are setting state to user witch is not relevant to the search.
try this:
filterArray = () => {
const { query, user } = this.state;
if(query.length > 0){
const searchResult = searchString.filter((el, i) => el[i].first_name.includes(query);
this.setState({ searchString: searchResult })
}
}
more info about filter method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter