API - display specific element based on api value in React

0 votes
25 views
added Feb 27 in API by lcjr First Warrant Officer (11,830 points)

Both Parent & Child communicate through apiValue that has passed as a prop to the BuddySearchGroup component. The value of apiValue comes from the state variable apiResponse in the parent component.

Parent component

import React, { useState, useEffect } from 'react';
import BuddySearchGroup from './search/SearchGroup';

const SearchResult = () => {
  // State to simulate API response
  const [apiResponse, setApiResponse] = useState(1); 

  // Function to manually set the API response
  const setManualApiResponse = (response) => {
    setApiResponse(response);
  };

  return (
    <div className="buddySearch_list">
      <BuddySearchGroup apiValue={apiResponse} />
    </div>
  );
};

export default SearchResult;

 

Child component 

import React, { useState, useEffect } from 'react';
// import { css, jsx } from '@emotion/react';

const SearchGroup = ({ apiValue }) => {
  // Dummy listing data
  const dummyListings = [
    { id: 1, title: 'Listing 1', price: '$100,000' },
    { id: 2, title: 'Listing 2', price: '$150,000' },
    { id: 3, title: 'Listing 3', price: '$200,000' },
    { id: 4, title: 'Listing 4', price: '$250,000' },
  ];

  return (
    <div>
      {apiValue === 1 && (
        <div>
          {dummyListings.map(listing => (
            <div className="buddySearch_listing" key={listing.id}>
              <h3>{listing.title}</h3>
              <p>{listing.price}</p>
            </div>
          ))}
        </div>
      )}
      {apiValue === 2 && <div>Div 2</div>}
      {apiValue === 3 && <div>Div 3</div>}
    </div>
  );
};

export default SearchGroup;
lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...