React: JavaScript library for creating interactive user interfaces in the browser
Example: complete state of a todo application
{
"newTitleInput": "learn Rea",
"todos": [
{ "id": 1, "title": "laundry", "completed": true },
{ "id": 4, "title": "shopping", "completed": true },
{ "id": 7, "title": "gardening", "completed": false }
]
}
possible appearance of a todo application:
example: component structure in a todo application
Example: components, state and props in a todo application
simple code example with state and JSX:
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<div>current count: {count}</div>
<div>
<button onClick={() => setCount(count + 1)}>
increment
</button>
</div>
</div>
);
}
options:
common functionality:
example slideshow component that demonstrates:
online version on Codesandbox: https://codesandbox.io/s/slideshow-cn6m5
in App.js / App.tsx:
import Slideshow from './Slideshow';
// ...
return (
// ...
<Slideshow />;
)
import { useState } from 'react';
const baseUrl = 'https://picsum.photos/300/200?image=';
function Slideshow() {
const [img, setImg] = useState(0);
const imgUrl = baseUrl + img.toString();
function goToPrevImg() {
setImg(img !== 0 ? img - 1 : 0);
}
return (
<div>
<h1>Image {img}</h1>
<button onClick={() => setImg(0)}>start</button>
<button onClick={() => goToPrevImg()}>prev</button>
<img src={imgUrl} alt="slideshow" />
<button onClick={() => setImg(img + 1)}>next</button>
</div>
);
}
export default Slideshow;
function Slideshow() {
// ...
}
A component is defined as a function that returns an XML tree
The function is called every time the component needs to be (re-)rendered
Component names always start with capital letters
const [img, setImg] = useState(0);
A component can have internal state entries
useState
returns the current state entry and a corresponding setter on every render
const imgUrl = baseUrl + img.toString();
We should usually store the minimal state
Other values (like imgUrl
) can be derived from the state values
function goToPrevImg() {
setImg(img !== 0 ? img - 1 : 0);
}
functions that interact with state can be defined within the component function
return (
<div>
...
</div>
);
An XML tag switches from JavaScript to XML mode
<h1>Image {img}</h1>
A curly brace switches back to JavaScript
<button onClick={() => setImg(0)}>start</button>
<button onClick={() => goToPrevImg()}>prev</button>
<img src={imgUrl} alt="slideshow" />
<button onClick={() => setImg(img + 1)}>next</button>
Event handlers can be defined as JavaScript functions