React Cheat Sheet
Basic React commands
Command | Notes |
npx create-react-app {app name} | Create new React app |
npm run build | Build React app - create a folder with files ready for deployment |
npm start | Run project locally |
npm test | run tests in React app |
npm eject | remove the single build dependency from your project |
JSX
JSX allows us to write HTML elements in JavaScript and place them in the DOM. Basically, it converts HTML tags into react elements.
Injection JS into HTML
'Hello world' will be injected and displayed inside <div>
element
Element declaration
We can assign specific DOM fragments to a particular variable (element above) and then (re)use it everywhere.
Function injection
Not only string values can be injected into DOM. The result of the above case will be div with 7 inside it as addNumbers was injected into an element.
Attributes
JavaScript code can be also called for DOM element properties/events
Fragments
JSX syntax must have one top parent HTML element. When we don't want to pack our HTML into (for example) one div or other elements then we can use fragment
which won't be rendered in our HTML
Example:
or
References
We can refer to html element from JS
Declare a reference
Assign a reference to element
Use reference to interact with element
Tip: References works for the class component but not for function component (unless you use useRef hook, see Other hooks )
Components
"React lets you define components as classes or functions. Components defined as classes currently provide more features"
Function component
Sample component:
Sample component with parameters:
Class component
Sample component:
Sample component with the parameters:
Events
Sample onClick
event in an element:
onClick function:
Access to "this" inside event:
There are a few ways to achieve that:
bind this
Arrow function. For arrow function, you don't have to perform binding because arrow functions are performing this binding by themselves by referring to this with
_this
variable_this = this
or
Child event
We can call a function in parent component from the child component.
Child component (somewhere in code):
Parent component:
Conditional element
Show element depending on the implemented condition
Option 1:
then:
Option 2:
and then use the element variable in jsx
Option 3:
Option 4:
List of elements
The recommended way to show a list of the same components is to use the "map" function. Example:
Then just use listItems
element in your JSX DOM. Please note key
property inside - it is obligatory to identify particular row in list.
Content projection
Content projection is injecting some HTML from parent component to child component
Example:
Parent component:
Child (MyElement) component:
<h1>Hello world</h1>
will be injected to place where {this.props.children}
has been used, so MyElement will look like:
Higher order component
Create a parameterized component in order to reuse it in different ways.
Example:
Usage:
test
will be injected into className
Routing
The Router will be described with react-router-dom library usage, which is often recommended.
Install:
Sample presenting an area where components matching to current URL will be rendered:
Link changing current url:
Tip: Route and Link need to be in same Router element
Nested routing
Parent:
SomeComponent:
Routing with parameters
and then in SomeComponent we have access to:
Authentication
Good idea is to create a custom Route component that will show specific component only when our authentication logic is passed:
Then instead of Route use PrivateRoute
State and life cycle
State
The state decides about the update to a component’s object. When state changes, the component is re-rendered.
Declaring initial state:
Using state:
Updating state:
After setState component will be re-rendered
Life cycle
Life cycle | Notes |
componentDidMount | Called at the beginning of component life - when a component has been rendered |
componentWillUnmount | This method is called before the unmounting of the component takes place. |
componentWillUpdate | Before re-rendering component (after change) |
componentDidUpdate | After re-rendering component (after change) |
componentDidCatch | Called when an error has been thrown |
shouldComponentUpdate | Determines whether a component should be updated after a change or not |
getDerivedStateFromProps | Called at the beginning of component life and when props/state will change |
getSnapshotBeforeUpdate | Called just before rerendering component - in order to save state |
Note Deprecation alert for componentWillUnmount and componentWillUpdate. This can cause memory leaks for server rendering.
Example:
Forms
Sample form:
Validation is described here: https://webfellas.tech/#/article/5
Http requests
There are a lot of ways to communicate with our backend API. One of them is to use Axios library.
Install: npm install axios
Example with GET:
Example with POST:
Example with async call:
Tests
Useful libs:
npm install --save-dev jest
to run tests
npm install --save-dev @testing-library/react
set of functions that may be useful for tests in React
Sample tests:
Interaction
Click on element:
Change value in input:
Check if element contains class
Mocking http
npm install axios-mock-adapter --save-dev
Example:
With specific parameter
Mocking components
Example:
Context
Context is a "bag" for some data common for node of components.
Declare context:
'red' is default value
Create context and distribute it to child component:
Use it in child component:
Use it in child component outside render function:
Hooks
Hooks let us use in functions React features dedicated previously for only classes, like state.
Basic hooks
useState hook
Can replace state managment
count
can be used to read data
0
is the default value for count
setCount(10)
is a function to change count state value
useEffect hook
Can replace componentDidMount
, componentDidUpdate
, componentWillUnmount
and other life cycle component events
Instead of using componentDidMount, componentDidUpdate we can use useEffect hook like this:
In order to act as componentWillUnmount:
useContext hook
Hooks for context implementation. See Context
Parent:
Child:
Other hooks
Hook | Usage | Notes |
useReducer | const [state, dispatch] = useReducer(reducer, initialArg, init); | Used for redux |
useCallback | const memoizedCallback = useCallback(() => {doSomething(a, b);},[a, b],); | Returns a memoized callback |
useMemo | const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]); | Returns a memoized value. |
useRef | const refContainer = useRef(initialValue); | Hooks for element reference |
useDebugValue | useDebugValue(value) | Display information in React DevTools |
Custom hook
Custom hooks can be created. Sample implementation:
TypeScript in React
Add to project commands
npx create-react-app my-app --typescript
- new app with TypeScript
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
- add TypeScript to existing project
npx tsc --init
- init tsconfig
Add type for custom DOM element
Interview questions
Q: How can we declare the component??
A: Use class extending React.Component or use function with React.FC type returning JSX.
Q: What is a difference between function component and class component?
A: Components defined as classes currently provide more features. Anyway, hooks can change that.
Q: In what type of component can we use hooks?
A: Function component
Q: How can we inject some HTML from parent component to child component?
A: Using content projection - > this.props.children will keep parent html element. See Content projection
Q: Describe useEffect hook
A: UseEffect can replace componentDidMount, componentDidUpdate, componentWillUnmount and other life cycle component events. See Basic hooks
Q: What is the difference between state and props??
A: The state decides about the update to a component’s object. When state changes, the component is re-rendered. Props are parameters passed from parent component to child component.
Q: What is a higher-order component??
A: Basically its's parameterized component. It allows reusing of a particular component in many ways. Sample implementation:
usage:
Q: What is JSX?
A: JSX allows us to write HTML elements in JavaScript and place them in the DOM. Basically, it converts HTML tags into react elements. See JSX
Q: How can we create new react app?
A: Using command npx create-react-app {app name}
Q: What will be the result of npm eject
?
A: Webpack for React application won't be handled automatically anymore. We will have access to Webpack configuration files in order to customize it to our needs.
Last updated