RyuH.
RyuH.

Reputation: 89

In react, how to use condition to create a custom search functionality?

I have a state of projects which is of type an array that contains the following data.

projects array

Using this data, I need to filter the user's result based on search input that matches with company_name, project_name, project_description, release_name, and release's description

this.state = {
  projects: [],
  searchfield: ''
};

onSearchChange = (event) => {
  this.setState({ searchfield: event.target.value })
}

<input type="text" placeholder="Search" className="form-control search-input" onChange={this.onSearchChange.bind(this)} />

render() {
    return(
        const filterProjects = this.state.projects.filter(data => {
            // filter projects based on project's name
          return data.project_name.toLowerCase().includes(this.state.searchfield.toLowerCase());
        })
    )
}

At the moment, I am only able to filter the result according to keywords that matches with project's name.

Hw can I use other properties or add a condition to filter data based on other properties as well?

Upvotes: 1

Views: 264

Answers (1)

charlietfl
charlietfl

Reputation: 171669

If you want to see if a term exists in any of those fields you can use Array#some()

const filterFields = ['company_name', 'project_name', 'project_description', 'release_name', 'descrip'];

const { projects, searchfield) = this.state;

const term = searchfield.toLowerCase(); 

const filterProjects = projects.filter(data => {  
  return filterFields.some(field => data[field].toLowerCase().includes(term))
});

Upvotes: 2

Related Questions