Vamsi
Vamsi

Reputation: 151

How to pass an Array from Child component to Parent Component in react

How to pass an Array from Child component to Parent Component in react this is my code

This is my Parent component

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

export default class Parent extends Component {
    render() {
        return (
            <div>
                <Child></Child>
            </div>
        )
    }
}

This is Child component

import React, { Component } from 'react'

export default class Child extends Component {
    render() {
        const students = ['Mark','John'];
        return (
            <div>
            </div>
        )
    }
}

Upvotes: 0

Views: 83

Answers (1)

David R.
David R.

Reputation: 361

Use React Components States and Props to achieve this:

Parent:

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

export default class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {data: []} // Initialize the State
        this.onChildData = this.onChildData.bind(this); // Bind the helper method
    }

    /*
     * This method is just to update the state with new data incoming from Child
     * You can even inline this in your 'render' method
     */
    onChildData(data) {
        this.setState({data});
    }

    render() {
        return (
            <div>
                /*
                 * Add a 'onData' prop to invoke from Child
                 * It will work as a callback
                 */
                <Child onData={this.onChildData}></Child>
            </div>
        )
    }
}


Child:


import React, { Component } from 'react'

const students = ['Mark','John'];

export default class Child extends Component {
    /**
     * componentDidMount is called by React immediately after this component is mounted
     * We use it to call the 'onData' callback and send data to the parent
     */
    componentDidMount() {
        this.props.onData(students);
    }

    render() {
        return (
            <div>
            </div>
        )
    }
}

Upvotes: 3

Related Questions