console.log('Hello world');
let name = 'Martin';
name = 'Lucas';
const surname = 'Nuc';
// 1) double quotes
let name = "Martin";
// 2) single quotes
let name = 'Martin';
// 3) backticks
let name = `Martin`;
let fullName = `${name} Nuc`;
let name = 'Martin';
console.log(name.toUpperCase());
let characters = name.split('');
console.log(characters); // ['M', 'a', 'r'...]
later...
let a = 5;
if (a === 5) {
console.log('is five');
}
for (let i = 0; i < 10; i++) {
// ...
}
let i = 0;
while(i < 10) {
// ...
i++;
}
function add(a, b) {
return a + b;
}
// 1) named function
function hello() {
console.log('hello');
}
// 2) anonymous function
const hello = function() {
console.log('hello');
}
// 3) anonymous using arrow function
const hello = () => console.log('hello');
named
anonymous
// with body
const one = () => {
return 1;
};
// single returned statement
const two = () => 2;
let teacher = {
firstName: 'Martin',
surname: 'Nuc',
age: 32
}
let teacher = {
firstName: 'Martin',
surname: 'Nuc',
age: 32
}
// using dot notation
teacher.age = 33;
// using key name
teacher['age'] = 33;
let keyName = 'age';
teacher[keyName] = 33;
let firstName = 'Martin';
let age = 32;
// create object
let teacher = {
firstName: firstName,
age: age
}
// shorthand:
let teacher = {
firstName,
age
}
const martin = {
firstName: 'Martin',
age: 36
}
const richMartin = {
...martin,
money: 1000000
}
let teacher = {
firstName: 'Martin',
age: 32
}
let teacherTwo = teacher;
teacherTwo.age = 55;
console.log(teacher.age); // ????
const obj = {
one: function() { return 1; },
two: () => 2,
three() {
return 3;
}
};
obj.four = () => 4;
obj.one();
obj.two();
obj.three();
obj.four();
const obj = {
firstName: 'Martin',
surname: 'Nuc',
age: 32
};
const { firstName, surname } = obj;
console.log(name, surname);
function printAge({age}) {
console.log(age);
}
printAge({
name: 'Martin',
age: 32
});
const obj = {
name: 'Martin',
surname: 'Nuc',
age: 32
};
const { name, surname, ...other } = obj;
console.log(other); // { age: 32 }
typeof 5 // 'number'
typeof 'hi' // 'string'
typeof {} // 'object'
typeof [] // 'object'
typeof undefined // 'undefined'
typeof null // 'object' !!
let items = [1, 2, 3]; // creation
items.push(4);
console.log(items); // [1, 2, 3, 4]
console.log(items.length) // 4
let arr = ['one', 'two', 'three'];
console.log(arr[0]); // 'one'
console.log(arr[1]); // 'two'
console.log(arr[5]); // undefined
const arr = ['one', 'two', 'three'];
const newArray = [...arr, 'four'];
let arr = [1, 2, 3, 4];
let output = arr.join('-');
console.log(output); // '1-2-3-4'
let arr = [1, 2, 3, 4];
arr.reverse();
console.log(arr); // [4, 3, 2, 1]
[1, 2, 3, 4].forEach(item =>
console.log(item)
);
let result = [1, 2, 3, 4].every(item =>
item > 0
);
console.log(result); // true
let result = [1, 2, 3, 4].map(item =>
item + 1;
);
console.log(result); // [2, 3, 4, 5]
let result = [1, 2, 3, 4].filter(x => x > 2);
console.log(result); // [3,4]
[1,2,3,4].reduce((accumulator, current) =>
accumulator + current
, 0); // 10
accumulator | current | result |
---|---|---|
0 | 1 | 1 |
1 | 2 | 3 |
3 | 3 | 6 |
6 | 4 | 10 |
'Good morning'.split(' '); // ['Good', 'morning']
let result = 'Good morning'
.replace('morning', 'afternoon');
class Dog {
bark() {
console.log('woof-woof');
}
}
let rex = new Dog();
rex.bark();
class Dog {
setName(newName) {
this.name = newName;
}
bark() {
console.log('woof-woof, I am ' + this.name);
}
}
let rex = new Dog();
rex.setName('Rex');
let lassie = new Dog();
lassie.setName('Lassie');
rex.bark(); // woof-woof, I am Rex
lassie.bark(); // woof-woof, I am Lassie
class Dog {
constructor(name) {
this.name = name;
}
bark() {
console.log('woof-woof, I am ' + this.name);
}
}
let rex = new Dog('Rex');
rex.bark(); // woof-woof, I am Rex
class Animal {
eat() {
console.log('yum yum');
}
}
class Dog extends Animal {
constructor(name) {
this.name = name;
}
bark() {
console.log('woof-woof, I am ' + this.name);
}
}
let rex = new Dog('Rex');
rex.bark(); // woof-woof, I am Rex
rex.eat(); // yum yum
console.log(1);
setTimeout(() => console.log(2), 1000);
setTimeout(() => console.log(3), 2000);
console.log(1);
setTimeout(() => console.log(2), 0);
console.log(3);
this
class Dog {
constructor(name) {
this.name = name;
}
bark() {
console.log('woof-woof, I am ' + this.name);
}
}
let rex = new Dog('Rex');
rex.bark();
let obj = {
name: 'Martin',
sayHi() {
console.log(this.name);
}
}
obj.sayHi();
let fn = obj.sayHi;
fn();
function fn(num) {
console.log(this, num);
}
// classic invocation
fn(1); // this = undefined
// call + apply
fn.call('test', 2); // this = 'test'
fn.apply('test', [3]); // this = 'test'
// bind
let bound = fn.bind('test');
bound(4); // this = 'test'
$('a').each(function() {
console.log(this.href);
});
let obj = {
name: 'Martin',
hi() {
console.log(this.name);
setTimeout(function () {
console.log(this.name);
}, 1000);
}
}
obj.hi();
let obj = {
name: 'Martin',
hi() {
console.log(this.name);
setTimeout(() => {
console.log(this.name);
}, 1000);
}
}
obj.hi();
obj = {a: 2, b: 3};
for(key in obj) {
console.log(key)
}
setTimeout(() => {
console.log('after 1s');
setTimeout(() => {
console.log('after another 1s');
setTimeout(() => {
console.log('after another 1s');
}, 1000);
}, 1000);
}, 1000);
promise
.then(fn1)
.then(fn2)
.then(fn3)
pending
rejected
fullfilled
.then(...)
.catch(...)
= instantiate a Promise object
function wait5seconds() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(), 5000);
});
};
wait5seconds().then(() => console.log('after 5s'));
shorthand for resolved / rejected promise
Promise.resolve()
Promise.reject()
function wait5seconds() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve([1, 2, 3]), 5000);
});
};
wait5seconds().then((data) => console.log(data));
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => reject('This is error'), 5000);
});
};
fetchData()
.then((data) => console.log('success', data))
.catch((error) => console.log(error));
Promise.resolve('hey')
.then(data => console.log(data)) // "hey"
.then(() => anotherPromise()) // async
.then(() => {
return 'hello'; // sync
})
.then(param => console.log(param)); // "hello"
async function countDown() {
console.log(3);
await wait(1000);
console.log(2);
await wait(1000);
console.log(1);
await wait(1000);
console.log('go!');
}
countDown().then(() => console.log('done'));
async function countDown() {
console.log(3);
await wait(1000);
console.log(2);
await wait(1000);
console.log(1);
await wait(1000);
console.log('go!');
}
countDown().then(() =>
console.log('done'));
function countDown() {
console.log(3);
return wait(1000)
.then(() => console.log(2))
.then(() => wait(1000))
.then(() => console.log(1)
.then(() => wait(1000))
.then(() => console.log('go!'))
}
countDown().then(() =>
console.log('done'));
async function fn() {
const data = await Promise.resolve('hello');
}
async function() {
try {
await Promise.reject('this is reason');
} catch (err) {
console.error(err);
}
}
function fetchData(url) {
return new Promise((resolve, reject) => {
setTimeout(() => {
Math.random() < 0.5 ? resolve(Math.random()) : reject('Fetching failed')
}, 1000);
})
}
function execute() {
const results = [];
fetchData('seznam.cz')
.then((seznamData) => results.push(seznamData))
.then(() => fetchData('google.com'))
.then((googleData) => results.push(googleData))
.catch(error => console.log(error))
.then(() => console.log('done'))
}
fetchData ramdomly fails
Dependency management
{
"name": "my-package",
"version": "1.0.0",
"description": "This is just description of my awesome package",
"main": "index.js",
"scripts": {
"dev": "nodemon --exec npm run start",
"start": "tsc && node dist/index.js",
"test": "mocha --opts mocha.opts"
},
"author": "Martin Nuc",
"license": "ISC",
"dependencies": {
"@types/chai": "4.0.4",
"@types/mocha": "2.2.43",
"@types/node": "8.0.28",
"@types/sinon": "2.3.4",
"chai": "4.1.2",
"mocha": "3.5.3",
"nodemon": "1.12.1",
"sinon": "3.2.1",
"ts-node": "3.3.0",
"typescript": "2.5.2"
}
}
package.json
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
Shortcut for start and test scripts only. For others you have to use npm run
Runs any script from npm.
👉
npm install lodash
installs lodash library:
import lodash from 'lodash';
lodash.difference([1, 2, 3], [2, 3]);
{
"name": "my-package",
"version": "1.0.0",
"description": "This is just description of my awesome package",
"main": "index.js",
"scripts": {
"dev": "nodemon --exec npm run start",
"start": "tsc && node dist/index.js",
"test": "mocha --opts mocha.opts"
},
"author": "Martin Nuc",
"license": "ISC",
"dependencies": {
"@types/chai": "4.0.4",
"@types/mocha": "2.2.43",
"@types/node": "8.0.28",
"@types/sinon": "2.3.4",
"lodash": "4.17.5",
"chai": "4.1.2",
"mocha": "3.5.3",
"nodemon": "1.12.1",
"sinon": "3.2.1",
"ts-node": "3.3.0",
"typescript": "2.5.2"
}
}
package.json
6.11.2
patch
minor version
major version
6.11.2
patch
minor version
major version
- major changes, breaks API
6.11.2
patch
minor version
- new features
- doesn't break API
major version
- major changes, breaks API
6.11.2
patch
- only bugfixes
minor version
- new features
- doesn't break API
major version
- major changes, breaks API
Client
Server
Database
HTTP
browser
request
html page
Client
Server
Database
HTTP
React in browser, mobile app...
API
request
data
Single page application
Web server
html, js
npm create vite@latest
Project name: … (react-skoleni)
Select a framework: › React
Select a variant: › JavaScript
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)
npm run dev
const label = React.createElement('a', {
href: 'https://google.com'
}, 'Go to Google.com');
<a href="https://google.com">Go to Google.com</a>
children
props
type
import React from 'react';
function App() {
return (
<div className="App">
Hello
</div>
);
}
function App() {
return React.createElement('div', { className: 'App' }, 'Hello');
}
import React from 'react';
function App() {
return (
<div className="App">
Hello
</div>
);
}
function App() {
return React.createElement('div', { className: 'App'}, 'Hello');
}
import React from 'react';
function App() {
return (
<div>
Yes
</div>
<div>
No
</div>
);
}
function App() {
return ????????
}
import React from 'react';
function App() {
return (
<>
<div>
Yes
</div>
<div>
No
</div>
</>
);
}
function App() {
return <h1>Hello</h1>;
}
function App() {
let something = 'hello';
return <div>{something}</div>;
}
function Array() {
let array = [1,2,3];
return <div>
{array.map((item, index) => <span key={index}>{item}</span>)}
</div>;
}
function NameComponent(props) {
return <h1>Hi, my name is {props.name}!</h1>;
}
function AnotherComponent() {
return <NameComponent name="Martin" />
);
Component
Component
Component
Component
Component
Component
Component
User info
ArticleList
Article
Today Weather
Article
I am smart 💡
function NameComponent(props) {
return <h1>{props.name}</h1>;
}
function App() {
return <NameComponent name="Martin" />
}
Hello | Hello | Hello | Hello |
---|---|---|---|
Hello | Hello | Hello | Hello |
Hello | Hello | Hello | Hello |
<Table columns={4} rows={3} />
<button type="button" onClick={() => console.log('Hello')}>
Hello world
</button>
import React, { useState } from 'react';
function Counter() {
const [name, setName] = useState('nobody');
function handleGiveName(name) {
setName(name);
}
return <div>
My name is {name}.
<button onClick={() => handleGiveName('Martin')}>
Give me name
</button>
</div>
}
initial value
import React from 'react';
export class MyComponent extends React.Component {
state = {
counter: 0
};
increment() {
this.setState({ counter: this.state.counter + 1 });
}
render() {
const { counter } = this.state;
return <div>
Counter: {counter}
<button type="button" onClick={() => this.increment()}>Increment</button>
</div>
}
}
export class NumberGeneratorClass extends React.Component {
constructor(props) {
super(props);
const generatedNumbers = [...Array(props.pregeneratedCount)].map(() => Math.random());
this.state = {
generatedNumbers
};
}
generateNew() {
this.setState({ generatedNumbers: [...this.state.generatedNumbers, Math.random()] });
}
render() {
const { generatedNumbers } = this.state;
return <div>
{generatedNumbers.map((num, index) => <div key={index}>{num}</div>)}
<button type="button" onClick={() => this.generateNew()}>Generate new</button>
</div>
}
}
function MyComponent() {
const random = Math.random();
if (random < 0.5) {
return <span>lower</span>
} else {
return <span>higher</span>
}
}
function MyComponent() {
const random = Math.random();
return <span>
{random < 0.5 ? 'lower' : 'higher'}
</span>
}
function MyComponent() {
const condition = true;
return <>{condition && <span>It's true</span></>
}
import './App.css';
function Component() {
return <div className="red">Hello</div>
}
.red {
color: red;
}
App.css
App.jsx
import styles from './Component.module.css';
function Component() {
return <div className={styles.red}>Hello</div>
}
.red {
color: red;
}
App.module.css
App.jsx
import cn from 'classnames';
function ValidationState() {
const [invalid, setInvalid] = useState(false);
return <div className={cn({ red: invalid })}>
Status
</div>
}
import cn from 'classnames';
import styles from './ValidationState.module.css';
function ValidationState() {
const [invalid, setInvalid] = useState(false);
return <div className={cn({ [styles.red]: invalid })}>
Status
</div>
}
export const MyMouse = () => {
const [mousePosition, setMousePosition] = useState({x: 0, y: 0});
useEffect(() => {
const onMouseMove = event => {
setMousePosition({
x: event.clientX,
y: event.clientY
});
};
window.addEventListener('mousemove', onMouseMove);
return () => {
window.removeEventListener('mousemove', onMouseMove);
};
}, []);
const {x, y} = mousePosition;
return (
<div>My mouse x position is {x} and y position is {y}</div>
);
};
function ChildComponent(props) {
return <button onClick={props.onTrigger}>emit event</button>;
}
<ChildComponent onTrigger={() => console.log('triggered')} />
parent component:
child component:
<MyBytton onClick={...}>
<Icon> Click me!
</MyBytton>
function MyButton(props) {
return (
<button className="blue-button" onClick={props.onClick}>
{props.children}
</button>
)
}
www.google.com
www.instagram.com
www.facebook.com
Toggle button
emit click
DropdownComponent
shows
function Component() {
const [inputName, setInputName] = useState(name);
return <>
{inputName}
<input
value={inputName}
onChange={(e) => setInputName(e.target.value)} />
</>
}
import axios from 'axios';
const payload = { name: 'Martin' };
const response = await axios.post('/api/users', payload);
console.log(response);
import axios from 'axios';
const payload = { name: 'Martin' };
axios.post('/api/users', payload)
.then(response => console.log(response));
GET https://api.chucknorris.io/jokes/random
Component
User info
JokeFetcher
Joke
I am smart 💡
data down
const useMouseMove = () => {
const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });
useEffect(() => {
const onMouseMove = (event) => {
setMousePosition({
x: event.clientX,
y: event.clientY,
});
};
window.addEventListener('mousemove', onMouseMove);
return () => {
window.removeEventListener('mousemove', onMouseMove);
};
}, []);
return { x: mousePosition.x, y: mousePosition.y };
};
debugger;
const MyContext = React.createContext(false);
function App() {
return <MyContext.Provider value={true}>
<Component />
</MyContext.Provider>;
}
function Component() {
const value = useContext(MyContext);
return <div>{value}</div>;
}
const MyContext = React.createContext(0);
function App() {
const [value, setValue) = useState(0);
return <MyContext.Provider value={{ value, setValue}}>
<Component />
</MyContext.Provider>;
}
function Component() {
const {value, setValue} = useContext(MyContext);
return <>
<div>{value}</div>
<button onClick={() => setValue(value + 1)}>Click</button>
</>;
}
function Component() {
const inputRef = useRef(null);
function handleClick() {
inputRef.current.focus();
}
return <div>
<input ref={inputRef} />
<button onClick={handleClick}>Focus the input</button>
</div>
}
Routable pages
Navbar
import { Outlet } from "react-router";
export function Layout() {
return <div>
<NavBar />
<Outlet />
</div>
}
Here other routes render
Routable pages
<Outlet />
<Navbar />
import { RouterProvider, createBrowserRouter } from 'react-router-dom';
const router = createBrowserRouter([
... // (later)
]);
export function App() {
return (
<RouterProvider router={router} />
);
}
const router = createBrowserRouter([
{
path: '/',
element: <Layout />,
children: [
{
index: true,
element: <Home />
},
{
path: 'about',
element: <About />
},
{
path: 'articles',
element: <ArticlesContainer />,
children: [
{
path: ':articleId',
element: <Article />
}
{
path: ':articleId/comments',
element: <ArticleComments />
}
]
}
]
}
]);
Must have <Outlet /> inside
Layout component
Routable pages
Navbar
<Outlet>
Routable pages
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/articles">Articles</Link>
<Link to="/articles/{articleId}">Specific article</Link>
const navigate = useNavigate();
navigate('/articles');
import { useParams } from "react-router-dom";
function Joke() {
const params = useParams();
return (
{params.category}
);
}
/path-segment/:pathParam/something?query1=one&query2=two
useSearchParams
useParams
GET https://api.chucknorris.io/jokes/random?category={category}