DevNotes
@devnotes ·
React Part 2: Components and JSX
Components are the building blocks of every React app, and JSX is how they describe what to show. JSX looks like HTML but follows JavaScript's rules.
A component is a function
Component names must start with a capital letter. <Badge /> is your component, while <badge /> would be treated as an unknown HTML tag.
Use it like a tag, as many times as you like:
The rules of JSX
- Return one parent element. Two elements side by side need a wrapper around them.
- Close every tag, even ones HTML lets you leave open:
<img />,<br />,<input />. classbecomesclassName, becauseclassalready means something in JavaScript. For the same reason,foron a label becomeshtmlFor.- Attribute names made of more than one word become camelCase:
onclickisonClick,tabindexistabIndex. The exceptions arearia-*anddata-*, which keep their dashes. - Inline styles take an object, not a string:
style={{ color: "red", fontSize: 18 }}. The outer braces mean "JavaScript goes here", and the inner ones make the object.
For rule 1, if you don't want an extra <div> on the page, wrap them in a fragment, <> and </>:
Curly braces: JavaScript inside JSX
Wrap any JavaScript expression in { } to use it in JSX:
An expression is anything that produces a value: a variable, some maths, a function call, a ternary. Statements like if and for don't work inside the braces. Do that work above the return, then use the result.
One component per file
As an app grows, give each component its own file:
export default makes the component available to other files, and import brings it in. The ./ means "starting from this file's folder".
Thinking in components
Open any app you use and try drawing boxes around its parts. A feed is a list of post cards. A post card has an avatar, a name, some text and a row of buttons. Each box you draw could be a component, and some of them, like the avatar, turn up all over the app. That's how React developers look at a screen.
Try it
Split your portfolio into components: Header, About, ProjectCard and Footer, each in its own file in src/components. Then put them together in App.jsx.
Next: React Part 3: Pass data with props
Join WIK to like and reply to DevNotes and see more like this.