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
To be a component, function returning JSX should be used as <Component /> and not as Component().
When a functional component is used as <Component /> it will have a lifecycle and can have a state.
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.
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
Or
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With