4IT580: Docs
4IT580 WebGitLab

2nd Theoretical Class:
React Cheatsheet

React

The library for web and native user interfaces

- react.dev

Components

component = a reusable and composable UI element for your app

You can compose, order and nest components:

Defining a component

A React component is a JavaScript function. React renders the component by calling the function.


Component names must start with a capital letter!

Resources:

JSX

JavaScript Syntax Extension

Fragment

A special React element to group multiple elements that do not need a wrapper HTML node:

Shorthand syntax:

Resources:

JavaScript in JSX:

Using curly braces: A window into the JavaScript world.

Any JavaScript expression will work inside the curly braces.

Using to render a list of items:

Resources:

Conditional rendering

You can use regular JavaScript syntax inside React components:

statement

Ternary operator

It works even inside JSX:

Logical operator

⚠️ Be careful - when you use a numeric value in the left side of the operator and it is , it will render the value.

Solution 1:

Use an expression that evaluates to a boolean value:

Solution 2:

Use a ternary operator falling back to :

Props

Syntax:

🚸 Children

The prop contains anything that is placed between the opening and closing tags.

Reference:

Events

Handling user interactions - click, hover, focus, change, submit, etc.

The event handler can be extracted into a constant:

Passing event handler functions

⚠️ When passing an event handler stored in a variable or a constant, only pass the reference to it, do not call it!

  1. Pass a reference to the function. React will call it when the button is clicked:

  1. Give React a new function. That function will call when clicked.

Same behavior as above. Nothing happens right away, but when you click the button, the arrow function runs, it calls , and you see the alert.

You can use this when you want to pass extra arguments or do more logic:


  1. Do not call immediately while React is rendering the button.

What happens when you do?

Event handlers as props

There is a naming convention to use for event handler props

Resources:

State

Adding memory to your components

🤔 Can't we just use a variable?

The console log seems to work fine, but the component is not updated:

Issue:

React will not know that the state has changed. We have to tell React about it.

Let's use a state variable

State is a memory inside a component.

The and constants can be named anything, but they are conventionally named and .

When the state changes, React re-renders that component and all its children.

Functions like are called hooks - they are special functions which use React features inside a component.

Hook names always start with followed by a capital letter.

Components can contain multiple hooks

State is local to a component instance

When multiple instances of the same component are rendered, each one has its own state.

Resources

More about hooks