Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

499
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda