Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS - how a child access it's parent's props?

How can a child access its parent's props? For instance,

A parent component - footer.jsx:

import React from 'react';
import $ from 'jquery';

import NavItem from './nav-item';

class Footer extends React.Component
{
    constructor(props) {
        super(props);
        this.state = {
            publicUrl: null,
            currentUrl: null,
            navitems: [],
        };
    }

    // Then fetch the data using $.getJSON():
    componentDidMount() {
        this.serverRequest = $.getJSON(this.props.source, function (result) {
            this.setState({
                currentUrl: window.location.href,
                publicUrl: result.publicUrl,
                navitems: result.nav
            });
        }.bind(this));
    }

    componentWillUnmount() {
        this.serverRequest.abort();
    }

    render() {
        var loop = this.state.navitems.map(function(item, index){
            return <NavItem key={index} item={item}></NavItem>;
        });

        return (
            <div>
                <div className="nav">
                    <ul>{ loop }</ul>
                    <p>{this.state.publicUrl}</p>
                    <p>{this.state.currentUrl}</p>
                </div>
            </div>
        )
    }
}

export { Footer as default }

A child component - nav-item.jsx:

import React from 'react';

class NavItem extends React.Component
{
    constructor(props) {
        super(props);
    }

    render() {
        return <li><a href={this.props.publicUrl + '/' + this.props.item.url}>{this.props.item.title}</a></li>
    }
}

export { NavItem as default }

results in footer.jsx (parent):

this.props.publicUrl // http://my-website.com

results in nav-item.jsx (child):

this.props.publicUrl // undefined but it should be http://my-website.com

Any ideas?

Sample data:

{
    "publicUrl": "http:\/\/my-website.com",
    "nav": [{
        "navId": "3",
        "title": "Home
        "code": "home
        "href": null,
        "style": null,
        "sort": "3",
        "url": "home
        "parentId": null,
        "totalChildren": "0",
        "createdOn": null,
        "updatedOn": null
    }, {
        "navId": "4",
        "title": "About
        "code": "about
        "href": null,
        "style": null,
        "sort": "4",
        "url": "about
        "parentId": null,
        "totalChildren": "0",
        "createdOn": null,
        "updatedOn": null
    }, {
        "navId": "5",
        "title": "Contact",
        "code": "contact",
        "href": "#contact",
        "style": null,
        "sort": "5",
        "url": "contact",
        "parentId": null,
        "totalChildren": "0",
        "createdOn": null,
        "updatedOn": null
    }]
}
like image 740
Run Avatar asked Nov 04 '16 08:11

Run


4 Answers

There is no way to access parent props in child component. you can achieve this in following two ways:-

  1. Pass values into child component from parent via props like this :- <NavItem key={index} publicUrl={this.state.publicUrl} item={item}></NavItem>.
  2. Set values in state and dispatch action from child to fetch values from state.

Also, I notice that you are setting values in state in componentDidMount, so either set default values for state in constructor OR check for undefined value in your child component

like image 198
Gaurav joshi Avatar answered Nov 15 '22 19:11

Gaurav joshi


Another solution to this is

<MyChildComponent {...this} />

This will pass all parent props to child, you can also pass specific props by

<MyChildComponent {...this.specificProps} />

Hope this helps.

like image 24
happy go lucky Avatar answered Nov 15 '22 17:11

happy go lucky


Check here

http://jsfiddle.net/z5m56sqn/

It is also possible to use this.handleChildClick.bind(null,childIndex) and then use this.state.childrenData[childIndex]

Note we are binding with a null context because otherwise React issues a warning related to its autobinding system. Using null means you don't want to change the function context. See also.

like image 28
Bhupinder kumar Avatar answered Sep 23 '22 04:09

Bhupinder kumar


I must bind this to the loop:

var loop = this.state.navitems.map(function(item, index){
            return <NavItem key={index} publicUrl={this.state.publicUrl} item={item}></NavItem>;
}.bind(this));
like image 31
Run Avatar answered Nov 15 '22 17:11

Run