DevNotes

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

JSX
function Badge() {  return <span className="badge">New</span>;}

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:

JSX
function App() {  return (    <div>      <h1>Courses</h1>      <Badge />      <Badge />    </div>  );}

The rules of JSX

  1. Return one parent element. Two elements side by side need a wrapper around them.
  2. Close every tag, even ones HTML lets you leave open: <img />, <br />, <input />.
  3. class becomes className, because class already means something in JavaScript. For the same reason, for on a label becomes htmlFor.
  4. Attribute names made of more than one word become camelCase: onclick is onClick, tabindex is tabIndex. The exceptions are aria-* and data-*, which keep their dashes.
  5. 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 </>:

JSX
return (  <>    <h1>Title</h1>    <p>Text</p>  </>);

Curly braces: JavaScript inside JSX

Wrap any JavaScript expression in { } to use it in JSX:

JSX
function Profile() {  const name = "Ravi";  const followers = 1250;
  return (    <div>      <h2>{name}</h2>      <p>{followers.toLocaleString("en-IN")} followers</p>      <p>{followers > 1000 ? "Popular" : "Growing"}</p>    </div>  );}

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:

JSX
// src/components/Badge.jsxexport default function Badge() {  return <span className="badge">New</span>;}
JSX
// src/App.jsximport Badge from "./components/Badge";

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

reactjavascriptwebdevbeginners

Join WIK to like and reply to DevNotes and see more like this.