How can i pass the hello const value which is in the ChildComponent to the App component and store it in the childProps variable of the App component on page load.
import React, { Component } from 'react';
class App extends Component {
render() {
var childProps ''; // I want store the passed const value in this variable;
return (
<div>
<ChildComponent />
</div>
);
}
}
export default App;
class ChildComponent extends Component {
render() {
const hello = 'Hope you are having a good day!';
return <h1>{hello}</h1>;
}
}
export default ChildComponent;
CodePudding user response:
There is no way to pass props from a child component to a parent component. However, we can always pass around functions from the parent to child component. The child component can then make use of these functions.
CodePudding user response:
You can assign a callback to child component from parent component, it will be called once the child is mounted. Store that value in parent class property , if re-render requires maintain a state.
App
class App extends Component {
helloCallback = (str) => {
this.childProps = str
}
render() {
return (
<div>
<ChildComponent helloCallback={helloCallback}/>
</div>
);
}
}
Child
class ChildComponent extends Component {
hello = 'Hope you are having a good day!'
componentDidMount() {
this.props.helloCallback(this.hello)
}
render() {
return <h1>{this.hello}</h1>;
}
}
