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.
<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'
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With