Home > Software design >  Adding error message to react search filter
Adding error message to react search filter

Time:11-01

I am trying to implement a search filter in React. I am able to get the filter working, How do I add a error message here when there is no search result

export default class Search {
  ...

 search = (event) => {
 let word = event.target.value;
 this.setState({ search: word });
 };

  render() {
  const datas = data
  .filter((item) => {
    if (this.state.search == null) return item;
    else if (
      item.name.toLowerCase().includes(this.state.search.toLowerCase())
    )
      return item;
  })
  .map((item) => {
    return (
      <div>
        <p>{item.name}</p>
      </div>
    );
  });

return (
  <div>   
    <input
      type="text"
      placeholder="Search"
      onChange={(e) => this.search(e)}
    />
    {datas}
  </div>
  );
  }
}

this is my code. but i am not able to conditional render it and add a error meessage, if no results found

CodePudding user response:

Simply render some error message if datas is empty:

export default class Search {
  ...

 search = (event) => {
 let word = event.target.value;
 this.setState({ search: word });
 };

  render() {
  const datas = data
  .filter((item) => {
    if (this.state.search == null) return item;
    else if (
      item.name.toLowerCase().includes(this.state.search.toLowerCase())
    )
      return item;
  })
  .map((item) => {
    return (
      <div>
        <p>{item.name}</p>
      </div>
    );
  });

return (
  <div>   
    <input
      type="text"
      placeholder="Search"
      onChange={(e) => this.search(e)}
    />
    {datas.length === 0 ? 'No results were found' : datas}
  </div>
  );
  }
}
  • Related