I am just curious why we have to enclose a component name in tags when we render it. We can do without it also.
For example
function TemporaryName() {
return (
<div>
<h1>Stack Overflow Question</h1>
<h1>Stack Overflow Question</h1>
</div>
)
}
ReactDOM.render(<TemporaryName />, document.getElementById("root"))
This is enclosed and the line
ReactDOM.render(TemporaryName(), document.getElementById("root"))
also gives the same result. I know there has to be some meaning to it and I want to know why? Please help
CodePudding user response:
Your second example is calling TemporaryName as a function, and then passing the output to render. Basically, it's as though you wrote:
ReactDOM.render((
<div>
<h1>Stack Overflow Question</h1>
<h1>Stack Overflow Question</h1>
</div>
), document.getElementById('root'))
It's fine to pass a <div>
into ReactDOM.render
, so you didn't see a problem, but you will run into issues with more complicated components. As soon as you try to use any hooks in TemporaryName
, you will get an error. You'll be trying to call the hooks before calling ReactDOM.render
, which does not work.
Option 1 will work with hooks. With that, you use the JSX tags to create a react element, and pass that element into ReactDOM.render
. This doesn't call your function at this time, so there's no misuse of hooks. A little later, react will call your component and the hooks will work since we'll be in the middle of react's render cycle.
Example of something that will fail with the second approach:
function TemporaryName() {
const [name, setName] = useState('Stack Overflow');
return (
<div>
<h1>{name} Question</h1>
<h1>{name} Question</h1>
</div>
)
}
CodePudding user response:
Maybe because when you're declaring your component you're declaring a function: function TemporaryName()