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
````
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With