this may sound silly but I can't find a guide to this.
what I'm trying to do is changing a variable named update
in parent.
and in the parent DOM do :
<Child update={this.state.update} />
and in the child instead of picking it up between render and return (with const {update} = this.props
) and only being able to use it in the DOM, I'd like to pick it up in the section between the constructor and render and use it in a function there.
You can access the props
to the component anywhere in the component whether it be the constructor, lifecycle functions, render or custom functions.
The only thing that you need to know is that constructor, lifecycle methods and render function
are already have binding
to the context of the React component, but for custom function
you need to add binding yourself. Binding can be done in the constructor
or by declaring the functions as arrow functions
.
Check this answer on why you need to bind custom functions: Why do we need to bind function and eventHandlers in React and what is the difference between the different binding methods
For your case
<Child update={this.state.update} />
where Child could be
class Child extends React.Component {
componentDidMount() {
const {update} = this.update || {};
console.log(update);
this.somefunc();
}
somefunc = () = {
const {update} = this.update || {}; //After function is binded, you can do the same thing here too
console.log(update);
}
}
React has a lifecycle of functions called on a component: https://reactjs.org/docs/react-component.html
On startup of component you can use componentDidMount()
if you want to change state based on props change use: componentWillReceiveProps()
Otherwise if you want the result of that function to use as data for in your view (but just manipulated). Than make a seperate function also called: computed property of computed function. (because the result is computed based on current state/props). React will make sure you don't re-render/compute unnecessary.
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