Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the different between react component and function as component in react

I'm very confused learning react. For example I have very simple react component

export default function Foo(){
    return(
        <div>
            <div>some text</div>
        </div>
    )
}

And I want to add a child component:

export default function Foo(){

    const Bar  = ()=>{
        return (
            <input placeholder="some input"/>
        )
    }
    return(
        <div>
            <div>some text</div>
        </div>
    )
}

And as much as I know, I can use this component in two ways:

1. Use as function

return(
        <div>
            <div>some text</div>
            {Bar()}
        </div>
    )

2. use as component:

 return(
        <div>
            <div>some text</div>
            <Bar/>
        </div>
    )

What exactly different between these two? I thought it was same, until I faced an issue with input field, that if I use component as <Bar/>, The focus on input field will be lost after I enter first letter

Demo here: https://codesandbox.io/s/gifted-archimedes-l7bce7?file=/src/App.js

So what is the exact problem here? I code as component all the time, as per my understand <Bar/> is same as Bar() when it return react component

Am I right or not?

Edit: I found this blog, and it very close to this question and it great too :) https://dev.to/igor_bykov/react-calling-functional-components-as-functions-1d3l?signin=true

like image 749
CODEforDREAM Avatar asked Sep 10 '25 22:09

CODEforDREAM


2 Answers

  1. To be a component, function returning JSX should be used as <Component /> and not as Component().

  2. When a functional component is used as <Component /> it will have a lifecycle and can have a state.

  3. When a function is called directly as Component() it will just run and (probably) return something. No lifecycle, no hooks, none of the React magic.

The above 3 statement is the answer to your probem.

When you call the component as {Child()}, it does not have any lifecycle or hook and when you call as , it has it's own lifecycle and hooks this is why you are facing those problems.

For more read on this topis: Link.

like image 129
Hritik Sharma Avatar answered Sep 13 '25 13:09

Hritik Sharma


I have seen your codesand box demo, form there I think that the reason for losing focus from input field is the place where you have used useState.

Your can do two things here that's:

Either

  1. Pass the state as props from parent to child component.

Or

  1. use useState inside your child component as the parent does not require the state value I prefer the second way.

You can Read this for more knowledge of where to put the useState and when do you really need to use useState.

like image 21
Meet Bhalodiya Avatar answered Sep 13 '25 11:09

Meet Bhalodiya