0

In a class component we can do this:

class Block extends React.Component {
  public static customFunction1(){
    return whatever;
  }
  
  public static customFunction2(){
    return whatever;
  }

  render(){
     return <Component />
  }
}

So with the above component, we can directly use <Block /> wherever we want, and also utilize Block.customFunction() and the other one as well.

Now talking about Functional Component:

We tried doing

const Block = () => {
  return <Component />
}

Block.customFunction1 = () => {
  return whatever;
}

Block.customFunction2 = () => {
  return whatever;
}

People are not recommending the above approach. I'm wondering what should be the approach which attaching methods to Functional Component?

7
  • Why not passing them as props - Block({ canClick, canSpan }) {}? Commented Sep 12, 2022 at 19:52
  • 4
    What are you trying to do with those functions? Commented Sep 12, 2022 at 19:53
  • Those functions are being used by parent component. Commented Sep 12, 2022 at 19:55
  • 1
    The parent component should control whether the child is clickable/span-able. Commented Sep 12, 2022 at 19:56
  • 1
    My answer: Don't do this. Commented Sep 12, 2022 at 20:00

1 Answer 1

1

I don't think that there is actually a real relevance to do it like that. If you would use TypeScript for instance, you would make typing of this part of the code harder and there are actually other "reserved" properties that are used by React, e.g. "propTypes" or "displayName". That is the reason why you shouldn't do it, as you did it.

Another approach just for grouping these kind of elements that is more clean is the following:

Block.Component = () => {}

Block.onClick = (props) => {
  return true/false
} 

Block.onSpan = () => {
  return true/false
}

Now you are not attaching the properties to the component that is used by React internally, but still have the grouping and flexibility you need.

Sign up to request clarification or add additional context in comments.

3 Comments

Ahh that's interesting. So Block.Component, can be used in any other element simply as <Block />? or we need to use <Block.Component />?
It would be the latter: <Block.Component />
I see so much limitations with functional components its unbelievable..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.