Passing array from child to parent component

 To pass the assigned_users array from a child component to its parent component, you need to follow these steps:

  1. Create a callback function in the parent component: This function will be responsible for receiving the assigned_users array.

  2. Pass the callback function to the child component as a prop: The child component can then call this function when it wants to send the assigned_users array to the parent.

  3. Call the callback function from the child component: Inside the child component, when you want to send the data to the parent (e.g., after updating assigned_users), you call the callback function with the updated array.


Parent Component

jsx
import React, { useState } from 'react'; import ChildComponent from './ChildComponent'; const ParentComponent = () => { const [assignedUsers, setAssignedUsers] = useState([]); // Callback function to update the parent state const handleAssignedUsersChange = (users) => { setAssignedUsers(users); }; return ( <div> <h1>Assigned Users in Parent: {assignedUsers.length}</h1> <ChildComponent onAssignedUsersChange={handleAssignedUsersChange} /> </div> ); }; export default ParentComponent;

Child Component

jsx
import React, { useState, useEffect } from 'react'; const ChildComponent = ({ onAssignedUsersChange }) => { const [assignedUsers, setAssignedUsers] = useState([]); useEffect(() => { // Whenever assignedUsers changes, send the new value to the parent onAssignedUsersChange(assignedUsers); }, [assignedUsers, onAssignedUsersChange]); const addUser = (user) => { setAssignedUsers((prevUsers) => [...prevUsers, user]); }; return ( <div> <h2>Assigned Users in Child: {assignedUsers.length}</h2> <button onClick={() => addUser('User 1')}>Add User 1</button> <button onClick={() => addUser('User 2')}>Add User 2</button> </div> ); }; export default ChildComponent;



Explanation:

  1. In the ParentComponent, a function handleAssignedUsersChange is defined,
    which updates the state assignedUsers when it's called.
  1. This function is passed as a prop onAssignedUsersChange to the ChildComponent.
  2. In the ChildComponent, whenever the assignedUsers state is updated
(e.g., when a user is added), the useEffect hook ensures that the updated assignedUsers
is passed to the parent by calling onAssignedUsersChange(assignedUsers).

Comments

Popular posts from this blog

useCallback hook in React

Enhance existing Laravel CRUD application with advanced search and filtering capabilities.

VS code shortcut