Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

504
Vistas
How to pass an array as props in React component and use map on it?

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.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda