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

361
Visualizações
Call function from sibling component React hooks

How can I call a function that belongs to a sibling component either with props or context?

I've been trying to to this using props and context but I'm getting confused because I'm not passing variables but an actual function with parameters

I want to call the function handleSelectedUser that is inside the List component when I click the delete button in the Card component

Here it is in action in Replit

here is my code

App component:

function App() {
  const [currentUser, setCurrentUser] = useState(null)
  
   
  return (
    <main>
        <List 
          setCurrentUser={setCurrentUser} />
        <Card 
          currentUser={currentUser} 
          setCurrentUser={setCurrentUser}
          />
    </main>  );
}

List Component

function List({setCurrentUser}) {
  const [users, setUsers] = useState([])

  useEffect(() => {
    getUsers()
  }, [])

  async function getUsers(){
    const apiUrl = "https://randomuser.me/api?results=40"
    const result = await fetch(apiUrl)
    const data = await result.json()
    setUsers(data.results)
  }

  function handleDeleteSelectedUser(userToDelete){
    users.filter(user => user.phone != userToDelete.phone)
  }

  function handleSelectedUser(selectedUser){
    setCurrentUser(selectedUser)
  }
  
  
  return(
    <>
      <div>
        <h1>List</h1>
        {
          users.map((user) => 
          <li onClick={() => handleSelectedUser(user)} key={user.phone}>
          {user.name.first} {user.name.last}</li>)
        }
      </div>
    </>
  )
}

Card Component

function Card({currentUser, setCurrentUser}){
  
  function handleDelete(user){
    //Call handleSelectedUser in <List />
    setCurrentUser(null)
  }
  
  return (
    <div className="container">
      {currentUser && 
      <>
        <h2>{currentUser.name.first}'s Details</h2>
        <p>{currentUser.phone}</p>
        <button onClick={() => handleDelete(currentUser)}>Delete</button>
      </>
      }
    </div>
  )
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you're trying to "listen" for changes in a sibling component, a common approach is to use a shared prop as a hook dependency in the sibling.

For example:

function List({ currentUser, setCurrentUser }) {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    getUsers();
  }, []);

  async function getUsers() {
    const apiUrl = "https://randomuser.me/api?results=40";
    const result = await fetch(apiUrl);
    const data = await result.json();
    setUsers(data.results);
  }

  function handleDeleteSelectedUser(userToDelete) {
    users.filter((user) => user.phone != userToDelete.phone);
  }

  function handleSelectedUser(selectedUser) {
    setCurrentUser(selectedUser);
  }

  useEffect(() => {
    // do something when currentUser changes
    handleSelectedUser(currentUser);
  }, [currentUser]);

  return (
    <>
      <div>
        <h1>List</h1>
        {users.map((user) => (
          <li onClick={() => handleSelectedUser(user)} key={user.phone}>
            {user.name.first} {user.name.last}
          </li>
        ))}
      </div>
    </>
  );
}
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