Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define property in one component and pass to other component in reactJs?

I have a parent component and a child component, I want to pass property from Parent to Child by using {...this.props}, I dont want any action or reducer in the picture,Is it possible to do this?

My Child Component is like this:-

import React, { Component } from 'react'
import ReactDOM from 'react-dom'

 class SampleChild extends Component {
   constructor(props) {
     super(props)
   }
  render(){
    return(
      <div>This is Parent</div>
          )
         }
  }

 SampleChild.propTypes={
        Header:React.PropTypes.string.isRequired
 }
 export default SampleChild 

My Parent Component is like this:-

import React, { Component } from 'react'
import ReactDOM from 'react-dom'

class SampleParent extends Component {
  constructor(props) {
    super(props)
  }

  render(){
      return(
          <div><SampleChild {...this.props}/></div>
      )
  }
}
export default SampleParent

Now how can I pass the Header Property from the SampleParent Component to SampleChild?.Please assist me.

like image 564
Gorakh Nath Avatar asked Feb 17 '17 11:02

Gorakh Nath


2 Answers

<SampleParent Header="Hello from Parent" />

Will do the trick for you since you're spreading all props coming from SampleParent to SampleChild you need to make sure that the SampleParent just receives it as a prop if it's dynamic.

If it's a static prop you can define it in defaultProps for the SampleParent and you'll always pass the same string.

SampleParent.defaultProps = {
   Header: 'Hello from Parent'
}
like image 81
Henrik Andersson Avatar answered Nov 11 '22 18:11

Henrik Andersson


If you are just trying to pass "all" props from parent to child, you can do it this way.

From the component that is rendering the SampleParent ...

<SampleParent />

The SampleParent component:

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import SampleChild from './SampleChild';

class SampleParent extends Component {
  render() {
    return(
      <div>
        <SampleChild {...this.props} />
      </div>
    )
  }
}

SampleParent.defaultProps = {
  Header: "Header from parent"
}

export default SampleParent;

The SampleChild component:

import React, { Component } from 'react'
import ReactDOM from 'react-dom'

class SampleChild extends Component {
  render() {
    return(
      <div>
        <div>This is the Header passed from parent:</div>
        {this.props.Header}
      </div>
    )
  }
}

SampleChild.propTypes = {
  Header: React.PropTypes.string.isRequired
}

export default SampleChild;
like image 1
grizzthedj Avatar answered Nov 11 '22 19:11

grizzthedj