React apps are made out of components. A component is a piece of the UI (user interface) that has its own logic and appearance. A component can be as small as a button, or as large as an entire page.
React components are JavaScript functions that return markup
React component names must always start with a capital letter, while HTML tags must be lowercase
function MyButton() {
return (
<button>I'm a button</button>
);
}
export default function MyApp() {
return (
<div>
<h1>Welcome to my app</h1>
<MyButton />
</div>
);
}
The export default
keywords specify the main component in the file.
JSX is a syntax extension for JavaScript, but browsers don't understand JSX out of the box, so you'll need a JavaScript compiler to transform your JSX code into regular JavaScript.
JSX is stricter than HTML. You have to close tags like <br />
. Your component also can’t return multiple JSX tags. You have to wrap them into a shared parent, like a <div>...</div>
or an empty <>...</>
wrapper.
Comment: {/* I'm a comment */}
function MyButton() {
return (
<button>
I'm a button
</button>
);
}
export default function MyApp() {
return (
<div> {/* <> */}
<h1>Welcome to my app</h1>
<MyButton />
</div> {/* </> */}
);
}
In React, you specify a CSS class with className
. It works the same way as the HTML class
attribute
<img className="avatar" />
JSX lets you put markup into JavaScript. Curly braces let you “escape back” into JavaScript so that you can embed some variable from your code and display it to the user. For example, this will display user.name
:
return (
<h1>
{user.name}
</h1>
);
You can also “escape into JavaScript” from JSX attributes, but you have to use curly braces instead of quotes. For example, className="avatar"
passes the "avatar"
string as the CSS class, but src={user.imageUrl}
reads the JavaScript user.imageUrl
variable value, and then passes that value as the src
attribute:
return (
<img
className="avatar"
src={user.imageUrl}
/>
);