Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an Array from Child component to Parent component in react I know how to pass from parent t

Tags:

reactjs

I am working on a React project in that I am trying to pass an array from the child component to the parent component. But I don't know how to pass it

This is Parent component

import React from 'react';
import Child from './Child/Child'

function App() {
  return(
    <div className='App'>
      <Child></Child>
    </div>
  )
}

export default App

This is Child component

import React from 'react';

function Child() {
  const employees = ['Williams','Steve']
  return(
    <div className='Child'>
    </div>
  )
}

export default Child

````

like image 408
Vamsi Avatar asked Dec 05 '25 20:12

Vamsi


1 Answers

You can make use of hooks here.

Initialize a useState hooks in the parent component, then pass the set method as a prop to the child component.

Then in the child component you can assign new array value to the parent using the set method.

eg:

In parent:

    import React, {useState} from 'react';
    import Child from './Child/Child'

    function App() {
      const [arr, setArr] = useState([]);
      return(
        <div className='App'>
          <Child setArrFunc={setArr}></Child>
        </div>
      )
    }

export default App

In child component:

import React, {useEffect} from 'react';

function Child({setArrFunc}) {

  const employees = ['Williams','Steve']
  useEffect(()=> {
 setArrFunc(employees);
},[]);
  return(
    <div className='Child'>
    </div>
  )
}
export default Child;

//Or you can make use of onClick Function and make use of the setArrFunc inside clickHandle method

like image 67
Gowtham Karnan Avatar answered Dec 08 '25 10:12

Gowtham Karnan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!