N
N
Nikolai Antonov2016-11-30 11:41:20
JavaScript
Nikolai Antonov, 2016-11-30 11:41:20

How to get props in react static method?

I need to get props in a static property. Why can't I get props in a static method in the same way as in other methods?
My code:

class Field extends React.Component {
    
  static ifFieldNotEmpty() {
    const { fields } = this.props; // not works
    console.log(this);
  }
  
  render() {
    const { fields } = this.props; //  work fine
    
    return (
      <h2>render component</h2>
    );
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artcl, 2016-11-30
@Artcl

Because static works on the class, not on the instance.
In a static method, this.props cannot be accessed because it refers to the instance.

M
MorozoW, 2016-12-07
@MorozoW

In this example, you are doing a meaningless operation - in a static method, you work with the current context of the class instance (the context in this case is our this)
To solve the problem, you must either pass props as a parameter to the static method, or not work with the context, or work only with static class methods.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question