3.2: Single Element Rule
One of the first rules you need to know about any Component, whether it be functional or class, is that all JSX (the HTML looking stuff that we'll discuss later) must be wrapped inside a single parent element, a <div>
, an <h1>
, or inside of any other element with a closing tag.
Notice that you have done this in your FunctionalComponentDemo, where the 'Hello React' text is wrapped in the opening and closing <div>
tags:
Compare that 'return' code to the following:
What's different here?
Well, the second example will show an error, saying that 'JSX elements must have one parent'. This is because both of the <div>
tags are on the same level in the DOM tree. Again, there has to be a single parent in the return.
Making it work
If we did want to use the code in the second example, that is, two different <div>
tags in the same component, we would have to structure it like this:
Go ahead and run the app with that code. You should see it run correctly now.
Challenge
Before moving on, see if you can write the above component with Arrow Function syntax. It's very common to see that syntax in React components. If you've never seen Arrow Functions (also called Fat Arrow), try to research for a few minutes. Take 15 minutes to see if you can do this - without peeking at the answer in the next module.
Last updated