1

As I read here, one way in reactjs to reuse code is to put it in a "container" component, then pass it down to its child via props. Cool.

Problems rise to me when, in my IDE (VSCode), I need to go to the method/property implementation: if code is imported via oldSchool "import", then everything works by "ctrl+clicking" the method name; but if I'm inspecting a method/property passed via props by the parent component, then "ctrl+click" on the method name is useless:

<div onClick={props.**methodFromParent**()}>Click me</div>

That's pretty obvuios, because there are no refs in my child code about the parent component itself (they get composited in another component ad-hoc). So is there a way to have this feature back? Because is very usefull to me.

Nemus
  • 1,322
  • 2
  • 23
  • 47
  • Can you provide more code? Passing a function as a prop and executing it in a child component is perfectly fine. – Tobi Dec 23 '21 at 16:32
  • 1
    Sounds like you need proptypes (https://reactjs.org/docs/typechecking-with-proptypes.html) or typescript (https://www.typescriptlang.org/) – André Krosby Dec 23 '21 at 16:35
  • 1
    @Tobi I know that. My prolem is in my IDE: ctrl+click the method inside the child doesn't redirect me to the method implementation – Nemus Dec 23 '21 at 16:35
  • Ah, okay sorry. Yeah then the approach of @AndréKrosby is the right one, as there are no type and therefore definition references. – Tobi Dec 23 '21 at 16:38

1 Answers1

0

Can't be possible. If you define a method in the parent and pass it to the child you are not passing the mothod. What you actually are passing is a reference to a function and the child executes that function. Like you mentioned it is possible to reuse code that way. The child doesn't know what method will be passed. It is not a static binding. So the IDE can't know either.

You could have something like:

// Parent component
const add = (a,b) => return a+b;
const sub = (a,b) => return a-b;
 
return ( <>
  <child num=4 action={add}>
  <child num=7 action={sub}>
</>);
// Child component
return (
  <div>The result is {props.action(10, props.num)}</div>
);

As you see the property "action" doesn't relate to any particular method on the parent, it is just a property and the IDE can't show you a definition.

dnmeid
  • 386
  • 3
  • 4