Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we access props passed to the component in a custom function

Tags:

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.

like image 481
tatsu Avatar asked Oct 04 '17 07:10

tatsu


2 Answers

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);
    }
}
like image 81
Shubham Khatri Avatar answered Sep 30 '22 05:09

Shubham Khatri


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.

like image 29
Joel Harkes Avatar answered Sep 30 '22 05:09

Joel Harkes