React
Usage
Plain react usage is not anymore recommended (although possible).
You can use React without a framework, however most apps and sites eventually build solutions to common problems such as code-splitting, routing, data fetching, and generating HTML. These problems are common to all UI libraries, not just React.
By starting with a framework, you can get started with React quickly, and avoid essentially building your own framework later.
Options are:
- next.js
- Remix
- Gatsby
- Expo
Next.js
- Use create-next-app
> npx create-next-app@latest
- choose your options
- Tailwind or bootstrap?
- ESLint?
- Pages router (yes)
Since asp.net is bootstrap based, use that? Cam just copy-paste html from asp.net mvc to js.
Clean up initial code
- empty global.css and page.module.css
- clean out page.tsx
1 2 3 4 5 6 7 |
|
Add bootstrap support
> npm install bootstrap
Modify layout.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
Modify page.tsx to include bootstrap style class.
1 2 3 4 5 6 7 |
|
Add support for bootstrap js.
Create src/components/BootstrapActivation.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Modify layout.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
Include bootstrap js code in page.tsx for testing
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
|
MVC
- React is mostly about View
-
But can do all
- has local state and several global state libraries
- Components can contain just logic (Container vs Presentation components)
-
Abstraction is Component, not html vs js
JSX
- React handles markup syntax named JSX
- HTML in JavaScript
- Compiles to JavaScript
1 2 3 |
|
1 2 3 4 |
|
babeljs.io
Properties
class
->className
for
->htmlFor
- camelCased attributes
tabindex
->tabIndex
- Inline styles
{}
– js expression in JSX (no statements!){{…}}
js object in js
Since JSX is converted into JS, typos, missing tags, etc. are not allowed!
1 2 3 4 5 6 7 8 9 10 |
|
More about React
- React implements virtual DOM
- Synthetic events
- Isomorphic (serverside rendering)
- React Native
- JS in HTML vs HTML in JS
<li v-for="user in users">
- logic, data-binding, looping in HTML- vs
{users.map(createRow)}
Components
- 4 ways to create React component
- createClass
- ES class
- Function
- Arrow function
createClass
The original way - obselete
1 2 3 4 5 6 7 |
|
Class component
render()
is mandatory to implement.
1 2 3 4 5 6 7 8 9 10 11 |
|
Function/Arrow function
Function Component
1 2 3 4 5 6 7 |
|
Arrow function
1 |
|
Functional components - why?
- Easier to understand
- Avoid ‘this’
- Less transpiled code
- Less obscure code
- Better code completion & intellisense
- Code smell is easy to see (too many parameters)
- Easy to test
- Perform better
- There is talk, that classes are dropped in future React
When to use class component?
- Before react 16.8
- State, Refs, Lifecycle methods – Class
- After 16.8 – Hooks (released 16.02.2019)
- componentDidError, getSnapshotBeforeUpdate – Class
- All the other cases – function components are preferred
Specifics of components
- Components start with capital letter (even functional).
- JSX asumes that lower case elements are html, upper case React components
return (…);
- use parenthesis around JSX when JSX is multiline.- JSX can contain only one top level element – use
<>…
around mutilple upper-level tags. <>…
- JSX fragment. Avoids unneccesary divs. (alias to React.Fragment).
Example of components
1 2 3 4 5 |
|
1 2 3 4 5 |
|
Functional components Home
and Privacy
.
Example of components 2
- Header
- Html from asp.net
Danger
class
-> className
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
Data
-
React is only using one-way data binding!
-
Data is held in two places in every component
- Props
- State
-
Props are like html properties – for passing data down to component.
- Props are immutable – it belongs to parent component.
- Use parent provided callbacks to update
props
1 2 3 4 5 |
|
1 2 3 4 5 6 |
|
1 2 3 4 5 |
|
props - default values
1 2 3 4 5 6 7 8 9 10 |
|
State (class component)
- Props – immutable
- State – mutable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
State - class component
- Declare as property state in class
- Update with
this.setState({ properties to be updated })
-
Access with
this.state.property
-
Carefull with
this
!
Class component props and state
- Shape of state and props
React.Component<P,S>
P
– properties interfaceS
– state interface- Default is
{}
Props are accessible as this.props
. State as this.state
.
LifeCycle - Class components
-
Mounting
constructor()
static getDerivedStateFromProps()
render()
componentDidMount()
-
Updating (props or state change)
static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
-
Error Handling
static getDerivedStateFromError()
componentDidCatch()
-
Unmounting
componentWillUnmount()
REST client
- How can I make an AJAX call?
- You can use any AJAX library you like with React. Some popular ones are Axios, jQuery AJAX, and the browser built-in window.fetch.
- Where in the component lifecycle should I make an AJAX call?
- You should populate data with AJAX calls in the
componentDidMount
lifecycle method (class component). This is so you can usesetState
to update your component when the data is retrieved.
- You should populate data with AJAX calls in the
Axios based example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
Key
- Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.
- The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys.
- When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort.
- Keys used within arrays should be unique among their siblings. However they don’t need to be globally unique.
Shared state
- Pass state down via props (immutable in child component)
- Include callbacks to update parents state from child component
- Gets complicated quickly – “Prop Drilling” and callback hell
- State management – Context, Flux/Redux – coming….
Functional components
- Props – as parameters
- State, Lifecycle, … - hooks
Basic hooks
- useState
- useEffect
- useContext
- Additional Hooks
- useReducer
- useCallback
- useMemo
- useRef
- useImperativeHandle
- useLayoutEffect
- useDebugValue
https://reactjs.org/docs/hooks-intro.html
Hooks
Hooks are functions that let “hook into” React state and lifecycle features from function components.
useState
useState
is the HOOK! Returns array of state variable and update function. Parameter touseState
is the initial value of state variable.- You can use
useState
hook several times.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
useEffect
- The Effect Hook,
useEffect
, adds the ability to perform side effects from a function component. - It serves the same purpose as
componentDidMount
,componentDidUpdate
, andcomponentWillUnmount
in React classes.useEffect
runs after every render.
useEffect - no cleanup
useEffect runs after every render. Has access to state/prop variables.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
useEffect – cleanup
1 |
|
- If you need to call some function to clean up – return the callback function from the useEffect().
- Same code that sould run from componentWillUnmount() class lifecycle method.
useEffect
can be used several times – split unrelated logic.- NB! – pass second parameter – array of variables that are used in effect logic – to let React decide should useEffect run. If values are same between renders - effect will not run.
1 2 3 4 5 6 |
|
Returned function will run after previous render.
useEffect - cleanup - Axios example
- Do not update component when it is unloaded
- Cancel Axios request
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
Axios based example - func, hooks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|