3

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

````

Vamsi
  • 372
  • 6
  • 18

3 Answers3

3

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

0

If you want to pass something to the parent component the easiest way is to create a callback in Parent component that you use in Child component.

Pass props to parent component in React.js

Maciej Trojniarz
  • 702
  • 4
  • 14
0

In the parent define a method to handle the array:

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

function App() {
  const doSomething = (inputArray: string[]) => {
    // Do something with your array of strings in here
  };

  return (
    <div className='App'>
      <Child doSomethingMethod={this.doSomething}></Child>
    </div>
  );
}

export default App;

Then you can utilise it in the child:

import React from 'react';

function Child() {
  const employees = ['Williams','Steve'];
  const doingSomething = () => {
    // blah blah
    // this method is an example where it takes the employees array as a fixed
    // array predefined elsewhere (above)
    this.props.doSomethingMethod(employees);
  };

  const doSomethingElse = (inputArray: string[]) => {
    // this method takes arguments then pushes them into the method to pass
    // to the parent
    this.props.doSomethingMethod(inputArray);
  };

  return (
    <div className='Child'></div>
  );
}

export default Child
rrd
  • 5,789
  • 3
  • 28
  • 36