Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Here is a basic approach to displaying a list of objects obtained from an API in ReactJS and enabling users to filter them through their search inputs:

  1. Create a component that will fetch data from the API and store it in the component's state.
import React, { Component } from 'react';

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      search: ''
    };
  }

  componentDidMount() {
    fetch('api_url_here')
      .then(response => response.json())
      .then(data => this.setState({ items: data }));
  }

  render() {
    return (
      <div>
        {/* display the list of items */}
      </div>
    );
  }
}

export default MyComponent;
  1. Use the map method to iterate through the items in the state and display them as a list.
render() {
  const { items } = this.state;

  return (
    <div>
      <ul>
        {items.map(item => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
}
  1. Create an input field for users to enter their search queries and attach an onChange event listener to update the component's search state.
render() {
  const { items, search } = this.state;
  const filteredItems = items.filter(item =>
    item.name.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div>
      <input type="text" onChange={event => this.setState({ search: event.target.value })} />

      <ul>
        {filteredItems.map(item => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
}
  1. Use the filter method to filter the items based on the search query and display the filtered items in the list.
render() {
  const { items, search } = this.state;
  const filteredItems = items.filter(item =>
    item.name.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div>
      <input type="text" onChange={event => this.setState({ search: event.target.value })} />

      <ul>
        {filteredItems.map(item => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
}

This is just a basic approach to displaying and filtering a list of objects obtained from an API in ReactJS. Depending on your specific use case, you may need to modify this approach to suit your needs.