Components
React apps are made out of components. A component is a piece of UI that has its own logic and appearance. A component can be as small as a button or an entire page.
React components are JavaScript functions that return markup:
function MyButton(){
return (
<button> I'm a button </button>
);
}
Components can also be nested in other components :
export default function MyApp (){
return(
<div>
<h1> Welcome to my app </h1>
<MyButton />
</div>
);
}
Writing markup in JSX
The markup syntax above is JSX
JSX is stricter than HTML. We need to close each opening tag like <br />
A component cannot return multiple JSX tags. So we need to wrap them into a parent, like.. <div>...</div> or <>....</> wrapper.
To use JavaScript in JSX, we need to enclose it between curly braces {}.
Adding Styles
In React, we specify a CSS class with className. It works the same as class attribute in HTML.
Then write CSS in a separate file just like HTML.
Conditional Rendering
In React, there is no special syntax for conditions. So we use normal JS conditions to do so.
let content;
if (isLoggedIn) {
content = <AdminPanel />;
} else {
content = <LoginForm />;
}
return (
<div>
{content}
</div>
);
To keep the lines short and code clean, we can also use the "?" operator.
<div>
{isLoggedIn ? (
<AdminPanel />
) : (
<LoginForm />
)}
</div>
Rendering Lists
We rely on JS functions like "for loop" and "map()" function to render lists of components. Example:
const products = [
{ title: 'Cabbage', id: 1 },
{ title: 'Garlic', id: 2 },
{ title: 'Apple', id: 3 },
];
const listItems = products.map(product =>
<li key={product.id}>
{product.title}
</li>
);
return (
<ul>{listItems}</ul>
);
Note how <li> has a key attribute. For each element in list, a unique key is required.
React needs these keys to know what happened if you later insert, delete or reorder the items.
Responding to Events
We can respond to events in React just like HTML inside your components.
function MyButton() {
function handleClick() {
alert('You clicked me!');
}
return (
<button onClick={handleClick}>
Click me
</button>
);
}
Notice how
onClick={handleClick}
has no parentheses at the end! Do not call the event handler function: you only need to pass it down. React will call your event handler when the user clicks the button.