A React page is built from components: functions that return a description of part of the page. You write that description in JSX, a syntax that looks like HTML but lives inside JavaScript. In this lesson you turn a piece of plain HTML into a component, and fix each place where JSX differs from HTML by reading the error it causes. Those errors are the same ones you will meet for the rest of the course, so learning to read them now pays off.
Before You Start
You need first-app from
What is inside a React project,
with its files as the template created them. In a terminal in
react-foundations-practice/first-app, start the dev server with
npm run dev. Open the address it prints and the browser's developer console
(F12, or Cmd+Option+I on macOS).
What a Component Is
A component is a JavaScript function that:
- has a name starting with a capital letter, such as
BookCard; - returns JSX describing what to show.
// Illustrative fragment
function Greeting() {
return <p>Hello from a component</p>
}
You use a component as if it were an HTML tag: <Greeting />. React calls the
function and puts what it returns on the page. One component can use others,
which is how a whole page is assembled from small pieces.
The capital letter is how JSX tells the two apart: <p> is an HTML element,
<Greeting /> is your component. A lower-case name is treated as an HTML tag,
so <greeting /> would produce an unknown, empty element, as a later section
shows.
Start with Your Own App
Replace the template's page with your own. Open src/App.jsx and replace its
whole content with:
// src/App.jsx: first version, before the components exist
export default function App() {
return (
<main>
<h1>My reading list</h1>
</main>
)
}
Save. The page now shows just the heading. The template's App.css and images
are no longer used; you can leave those files where they are.
The parentheses around the returned JSX are only there so it can span several
lines. Without them, JavaScript would end the return statement at the end of
the first line.
Paste Some HTML into a Component
Here is a piece of HTML for one book on the list, as a designer might hand it over:
<div class="book-card">
<h2>The Lighthouse Ledger</h2>
<hr>
<p class="author" style="color: #555">by Mira Okafor</p>
</div>
<p>Recommended by the book club</p>
Create a new file, src/BookCard.jsx, with a component that returns that HTML
exactly as given:
// src/BookCard.jsx: the first paste, which is broken (do not keep)
export default function BookCard() {
return (
<div class="book-card">
<h2>The Lighthouse Ledger</h2>
<hr>
<p class="author" style="color: #555">by Mira Okafor</p>
</div>
<p>Recommended by the book club</p>
)
}
Then use it in App. Add the import at the top of src/App.jsx and the tag
under the heading:
// src/App.jsx: using the component (the full file is under "End State")
import BookCard from './BookCard.jsx'
export default function App() {
return (
<main>
<h1>My reading list</h1>
<BookCard />
</main>
)
}
Save both files. Instead of the page, Vite shows an error overlay: a panel over the page describing a problem it found while converting your file. The terminal running the dev server reports the error too, sometimes with a different first line. The next four sections fix the HTML one problem at a time.
Mistake 1: Every Tag Must Be Closed
The overlay begins like this. This extract was observed with Vite 8.3.5; line and column numbers depend on your file:
Transform failed with 2 errors:
[PARSE_ERROR] Expected corresponding JSX closing tag for 'hr'.
╭─[ src/BookCard.jsx:7:7 ]
│
5 │ <hr>
│ ─┬
│ ╰── Opened here
│
7 │ </div>
│ ─┬─
│ ╰─── Expected `</hr>`
Read it from the top. Transform failed means Vite could not convert the
file. Each [PARSE_ERROR] names one problem and the file, line and column
(src/BookCard.jsx:7:7). The drawing below it points at the code: the <hr>
on line 5 was opened and never closed, so when the parser reached </div>
on line 7 it expected </hr> first.
In HTML, some elements such as <hr>, <br>, <img> and <input> never
take a closing tag. In JSX, every element must be closed, either with a
closing tag or by ending the opening tag with />. Change <hr> to <hr />.
The overlay listed 2 errors. The other one says something like
Unexpected token. Did you mean {'}'} or }? and points at the closing
brace at the end of the file. That is a consequence of the first error: once
the parser lost track of the tags, everything after looked wrong. The errors are
not always listed in file order, so look first for the one that names a tag
and says where it was opened. Fix that one, save, and read the overlay again.
Mistake 2: Return One Thing
After closing the <hr />, the overlay changes:
Transform failed with 1 error:
[PARSE_ERROR] Adjacent JSX elements must be wrapped in an enclosing tag.
╭─[ src/BookCard.jsx:8:5 ]
│
8 │ <p>Recommended by the book club</p>
│ ┬
│ ╰──
│
│ Help: Did you want a JSX fragment `<>...</>`?
The component returns a <div> and, next to it, a <p>. A function can return
only one value, and each JSX element becomes one value. Two elements side by
side are like writing return a b.
There are two ways to make them one:
- Wrap them in another element, such as a
<div>or<section>. This adds an element to the page. - Wrap them in a Fragment, written
<>and</>. A Fragment groups elements for JSX without adding anything to the page. The overlay's Help line suggests exactly this.
Use a Fragment here, because the extra wrapper element has no purpose:
// src/BookCard.jsx: wrapped in a Fragment (still has two mistakes; do not keep)
return (
<>
<div class="book-card">
...
</div>
<p>Recommended by the book club</p>
</>
)
Mistake 3: style Takes an Object
Save, and the overlay disappears, but the page is blank. Vite converted the file; the problem now happens while React runs the component. The console has a red error (observed with React 19.3.1 in development):
The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.
In HTML, style is a string of CSS. In JSX it is a JavaScript object, with
property names in camelCase (marginRight, not margin-right). Values are
usually strings:
// Illustrative fragment
<p className="author" style={{ color: '#555' }}>
The double braces are two different things. The outer { } means "a
JavaScript value goes here", and the inner { color: '#555' } is that value:
an ordinary object. Change the style attribute to style={{ color: '#555' }}
and save. The card appears.
React stops rendering when a component throws an error like this one, which is why the whole page went blank rather than just this card. A blank page with a red console error is a runtime error; an overlay is a conversion error.
Mistake 4: className, Not class
The card is on the page, but the console still shows a warning:
Invalid DOM property `class`. Did you mean `className`?
(The console fills in class and className; some browsers show the raw
message with %s placeholders and the two words after it.)
JSX attributes are written with JavaScript names. class is a reserved word in
JavaScript, so JSX uses className. The page happens to look right, because
React passes class through, but the warning tells you the code is not
correct JSX, and you should fix it: change both class attributes to
className. Other attributes follow the same rule: HTML's for is htmlFor,
and multi-word attributes are camelCase, such as tabIndex and onClick.
aria-* and data-* attributes keep their dashes.
Putting JavaScript in JSX with Curly Braces
The card's text is typed straight into the JSX. To show values from JavaScript instead, put them inside curly braces:
// src/BookCard.jsx
export default function BookCard() {
const title = 'The Lighthouse Ledger'
const author = 'Mira Okafor'
return (
<>
<div className="book-card">
<h2>{title}</h2>
<hr />
<p className="author" style={{ color: '#555' }}>
by {author}
</p>
</div>
<p>Recommended by the book club</p>
</>
)
}
This is the finished BookCard. Braces can hold any JavaScript expression,
meaning anything that produces a value: a variable ({title}), a calculation
({pages * 2}), a function call ({title.toUpperCase()}) or a template literal.
They can appear in two places:
- As text between tags:
<h2>{title}</h2>. - As an attribute value, instead of quotes:
style={{ color: '#555' }}, orclassName={isCurrent ? 'book-card current' : 'book-card'}, which you will meet later.
Statements such as if or for cannot go inside braces, because they do not
produce a value. Later lessons show the expression-based alternatives. Quotes
and braces are different: title="title" is the text "title"; title={title}
is the variable's value.
Why the Capital Letter Matters
Try it. In src/App.jsx, temporarily write <bookCard /> instead of
<BookCard /> and save. The card disappears and two warnings appear (observed,
with the names filled in):
<bookCard /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.
The tag <bookCard> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.
A lower-case name is treated as an HTML element, so React creates an empty,
unknown <bookcard> element instead of calling your function. Change it back
to <BookCard />.
How Files Connect
BookCard.jsx uses export default, and App.jsx imports it with
import BookCard from './BookCard.jsx'. That is the module pattern from the
JavaScript check: one component per file as the default export, imported under
its own name. The ./ is required for your own files. Without it, the import
would look for a package called BookCard.jsx in node_modules.
A component's file name and function name do not have to match, but keeping them the same makes a project much easier to find your way around, and the course always does.
A Note on Class Components
Older code and tutorials sometimes define components as JavaScript classes:
class BookCard extends React.Component with a render() method. React still
supports them, but the React documentation does not recommend them for new
code. This course writes every component as a function. If you meet a class
component, recognise it as the older style for the same idea.
End State
The finished App uses BookCard and the NextUp component from the next
section:
// src/App.jsx
import BookCard from './BookCard.jsx'
import NextUp from './NextUp.jsx'
export default function App() {
return (
<main>
<h1>My reading list</h1>
<BookCard />
<NextUp />
</main>
)
}
Your Turn: Convert a Second Card
Make a NextUp component in src/NextUp.jsx from this HTML, add it to App
below BookCard, and fix every problem the overlay and console report. There
are three differences from JSX; try to find them from the messages, not by
reading ahead.
<aside class="next-up">
<!-- The next pick, chosen at the last meeting -->
<h3>Next up</h3>
<p>
Notes from the Night Train
<br>
by Kenji Arai
</p>
</aside>
Hints
- One of the messages is new: it mentions HTML comments. JSX has its own way to write a comment, using braces and the JavaScript comment syntax.
- One element is like
<hr>. - The console warning that remains after the page appears is one you have already fixed once.
Solution
// src/NextUp.jsx
export default function NextUp() {
return (
<aside className="next-up">
{/* The next pick, chosen at the last meeting */}
<h3>Next up</h3>
<p>
Notes from the Night Train
<br />
by Kenji Arai
</p>
</aside>
)
}
The three fixes:
- The comment. Vite reports
[PARSE_ERROR] HTML comments are not allowed in modules. Inside JSX, a comment is a JavaScript comment inside braces:{/* ... */}. It is not sent to the page at all. <br>must be closed:<br />. The overlay reportsExpected corresponding JSX closing tag for 'br', followed by follow-on errors about the</p>and the final brace. Those disappear once the first one is fixed.classbecomesclassName, which removes the console warning.
The order in which you meet them can differ. Vite reports one problem at a
time when one hides others, as the <hr> hid the two-root problem earlier.
Fix what is reported, save, and read again until the overlay and the console
are clear.
Check Your Understanding
- A teammate's page shows nothing where
<bookList />should be, and the console warns that the tag is unrecognised. What is wrong? - Why does
<p style="color: red">stop the whole page from rendering, while<p class="note">only produces a warning? - You need two sibling elements returned from a component, and the page's layout must not gain an extra element. What do you use?
Answer and Reasoning
- The name starts with a lower-case letter, so JSX treats it as an HTML element
instead of calling the
BookListcomponent. Use<BookList />, and check that the component is imported under that name. - React cannot apply a string as a style object, so it throws an error while
rendering, which stops the whole tree. An unknown attribute name like
classis only reported; React still passes it to the element. Both should be fixed, but only one breaks the page. - A Fragment,
<>...</>. It groups the elements for JSX and adds nothing to the page. A wrapper<div>would also compile but adds an element.
Reset and Clean Up
Stop the dev server with Ctrl+C. first-app is not used after this lesson: the
next lesson creates reading-list, the course's main project. You can keep
first-app to experiment in, or delete the first-app folder inside
react-foundations-practice.
References
- React: Writing Markup with JSX
- React: JavaScript in JSX with Curly Braces
- React: Component (class components)