Faheim Ahmad
Faheim Ahmad

Reputation: 1

Pass data from one component to another component without parent child relation

Here are my two components. Component 1:

var Main = React.createClass({
    getInitialState: function(){
    return{
    data: [],
    values:[],
    childRecord:[]
    };
    },
    componentDidMount: function(){
    $.ajax({
    url: "data.json",
    dataType: 'json',
    success: function(data) {
    this.setState({data: data});
    }.bind(this),
    error: function(xhr, status, err) {
    console.error(this.props.url, status, err.toString());
    }.bind(this)
    });
    render: function() {
    var that = this,
    data = this.state.data;
    if(this.state.data.length > 0) {
        data = this.state.data[0].values;
        data = this.state.data[0].values[0].children;
    }
    var data = this.state.data;
    if(this.state.data.length > 0) {
        data = this.state.data[0].values;
    }
    var nestedData = data.map(function(Record, id) {
     return(
            <Tile key={id} data={Record} child={data}/>
         );
    });
    return (
        <div className="row main-container">
         {nestedData}
        </div>
       );
     }
    });

    *Component 2:*

    var Tile=React.createClass({
    render:function(){
    return(
    <div className="row">
    <div className="tileForm">
    <h3>{this.props.data}</h3>
    </div>
    </div>
    );
    }
   });

I want to render some part of json in Tile Component. The other components have parent child relation so I can render the data easily, but I dont know how to render the data in Tile component since there is no relation b/w Tile Component and other components. I am using routing to call Tile component and rendering Main component by using DefaultHandler, this is not the complete code. Any kind of help will be appreciated. Thanks Fhm

Upvotes: 0

Views: 1532

Answers (1)

mrkcsc
mrkcsc

Reputation: 77

You want to use the Flux (or something similar) pattern for this use case: https://github.com/facebook/flux - it was designed to solve this exact problem.

You would encapsulate your data (the JSON payload) in a shared Store. Both your components could then read from this store independent of how they are related to each other.

If the data needs to change you would pair this store with an action creator that your components could call to trigger data refresh/mutate, etc.

This also is helpful for when you have a deep nesting of components because you can avoid having to deeply bubble down your data.

Upvotes: 2

Related Questions