Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does props in props.functionName only need to be called sometimes?

In react, specifically referencing the hooks/functional paradigm, when do you need to use props.functionName? As far as I can tell, if the functions are named the same, you can omit props as follows:

Parent.js

...
<Child functionName={functionName}/>
...

Child.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

...
functionName();
...

However, if the name changes, props must be referenced as follows:

Parent.js

...
<Child otherName={functionName}/>
...

Child.js

...
props.otherName();
...

Am I correct? If so, why use the second design pattern? (Perhaps just to call out that the function comes from a parent and isn’t defined at the child level. Or maybe some other reason?)

>Solution :

No. The name you use depends entirely on how the child component processes the props it is passed. How the parent component determines what value to pass is completely irrelevant.

If the props are placed in a variable named props then you need to access them through the object store in the variable.

const Child = (props) => {
    props.functionName();
    ...
}

If the first argument is destructured, then each property is stored in its own variable.

const Child = ({functionName}) => {
    functionName();
    ...
}

If the value is copied to another variable inside the component then you can also use the variable it was copied to.

const Child = (props) => {
    const functionName = props.functionName();
    functionName();
    ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading