Manoj L Nayak
Manoj L Nayak

Reputation: 29

How to pass array of data from one component to another component in reactjs

I have tried to pass array of data from parent component to child component, but in the child component I'm not getting the array of data.could you please correct me where I'm doing mistakes.

In parent component I'm getting the data from service: var tableNames = [DataService.getTableNames()]; passing the array to the child component: <DataQueryInterface tableNames={[tableNames]}/> In the child component I'm trying to destructuring like this: var tableNames = [props.tableNames]

could you please help me with this...

Upvotes: 0

Views: 1357

Answers (2)

factor5
factor5

Reputation: 330

If DataService.getTableNames() returns an array, you should just assign it like this var tableNames = DataService.getTableNames(); and then pass it to the component <DataQueryInterface tableNames={tableNames}/>.

Here is a simple example given what we know about the needs:

class DataService {
  getTableNames() {
    return ['John', 'Doe'];
  }
}
class Child extends React.Component {
  render() {
    const tableNames = this.props.tableNames;
    console.log('child names', tableNames)
    return (<div>{tableNames}</div>);
  }
}
class Parent extends React.Component {
  constructor() {
    super();
    const service = new DataService();
    this.tableNames = service.getTableNames();
    console.log('parent names', this.tableNames);
  }

  render() {
    return (<Child tableNames={this.tableNames}/>);
  }
}

React.render(<Parent />, document.getElementById('app'));

And here is a working jsfiddle as well https://jsfiddle.net/Lh54mfwa/

Upvotes: 0

Rikin
Rikin

Reputation: 5473

Here's how I would suggest to structure it:

var tableNames = [ DataService.getTableNames() ]; // Data returned by the function is the placed inside a new `[]`

If DataService.getTableNames() itself returns an array then you can directly assign it to tableNames like below:

var tableNames = DataService.getTableNames(); // no need to wrap that inside another []

Once you have that cleared, passing the array to the child component would be like below:

<DataQueryInterface tableNames={tableNames}/> 

In the child component you destructure like below:

var { tableNames } = props;
// tableNames now contains reference to passed on `[]` from parent.

Note props is an object that contains property names tableNames which contains reference to an array.

Upvotes: 1

Related Questions