Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data to child components in reactjs

I am working in reactjs application. I want to pass data to its child components. I am having Parent as parent component and Test1 and Test2 as its children components. Also I am having constant data in parent components. I want to pass same data in its all child components. How can I access this data in Test1 component Code of parent

import React, {PropTypes} from 'react'; 
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {load} from 'redux/modules/viewlodging';
import Test1 from './Test1';
import Test2 from './Test2';
@connect(
state => ({data: state.viewlodging.data}),
dispatch => bindActionCreators({load}, dispatch))
export default class Viewlisting extends React.Component {
static propTypes = {
data: PropTypes.object,
load: PropTypes.func.isRequired
}
render() {
const {data} = this.props;
return (
<div>
    <div className="row font14 relative">
        <div className="container relative">
            <div className="col-md-8">
                <div className="row details">
                    <{data.title}>
                </div>
            </div>
            <div className="col-md-4" >
                <Test1/>
                <Test2/>
            </div>
        </div>
    </div>
</div>
);
}
}

In Test1

import React from 'react';
export default class Test1 extends React.Component {
 render() {
 return (
      <div className="summary-info">
          <div>From Test1</div>
      </div>
    );
 }
 }

How to access data in Test?

like image 276
user1820017 Avatar asked Jul 22 '26 02:07

user1820017


1 Answers

Pass it as props and then access it with this.props.

In your parent add props which you want to pass :

<Test1 data={data}/>

in your child access to it with this.props :

<div className="summary-info">
   <div>From Test1 - this is from parent {this.props.data}</div>
</div>

Here is the fiddle

like image 73
Boky Avatar answered Jul 24 '26 16:07

Boky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!