Home > Enterprise >  How to pass an array as props in React component and use map on it?
How to pass an array as props in React component and use map on it?

Time:01-15

I'm developing an app which has a searchbar - when user type something, an API call is made and the json is being send back. In the code below an array called sampleList represents this json. The json is then passed to the List component to render a simple list. This is what I did, however it doesn't work. I'm a begginer in react and I have two main questions:

  1. how to show the List component when user clicks on a search button?
  2. how to properly pass props to List component?

Here's the code: Searchbar.tsx

const sampleList = [
    { id: 1, name: "a"},
    { id: 2, name: "b"},
];
 
const Searchbar = () => {
    const onSubmit = (e) => {
         sampleList = getJson();
    }
    return (
    <form className="search-form" onSubmit={onSubmit}>
        <input type="text"></input>
        <input type="submit"></input>
    </form>
    <List prop={sampleList}/>
)}

List.tsx

const List = ({sampleList}) => {
    
    return(
    <div>
        sampleList.map((item, index) =>
        <div key={item.id}>
            {item.name}
        </div>
    )
    </div>
)}

Any help would be greatly appreciated.

CodePudding user response:

const List = ({ prop }) => {
    return(
    <div>
        prop.map((item, index) =>
        <div key={item.id}>
            {item.name}
        </div>
    )
    </div>
)}

prop attribut will be the key of your simpleList value. The parameter of your List component will be a json object which is containing keys and values as your prop key. You can also change the name of your prop attribut to put list for instance.

If you want to show the List component when user clicks on a search button you can use state property. I hope this link will help you: https://reactjs.org/docs/state-and-lifecycle.html

CodePudding user response:

Ideally you will want to maintain two states inside Searchbar.

  1. for the json response
  2. for displaying the list on search submit

To put it simply whenever a state is updated, the component will re-render and hydrate the new values as present in that state.

const Searchbar = () => {
  const [searchResults, setSearchResults] = useState([]);
  const [searchComplete, setSearchComplete] = useState(false);

  const onSubmit = async (e) => {
    const sampleList = await getJson();
    setSeatchResults(sampleList); // This will cause a state update and then pass the property along to the list component

    setSearchComplete(true); // This enable showing the list component now that the search is complete
  };

  return (
    <form className="search-form" onSubmit={onSubmit}>
      <input type="text"></input>
      <input type="submit"></input>
    </form>
    { searchComplete && <List prop={searchResults} /> }
  );
}

As for the list component, your code looks just fine. You just need to rename the sampleList to prop as you are passing the search results as prop in the above component

const List = ({prop}) => {
  return (
    <div>
      prop.map((item, index) =>
        <div key={item.id}>
          {item.name}
        </div>
      )
    </div>
  );
};

A piece of advice, always use async-await when making calls to apis. And ensure good error handling to avoid all scenarios.

  •  Tags:  
  • Related