React Flashcards

1
Q

What is React?

A

React is a JavaScript library to facilitate the creation of interactive, stateful and reusable UI components.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the virtual DOM?

A

It is an abstraction of the HTML DOM. It allows React to do its computations within the abstract DOM without the real DOM operations, often slow and browser-specific.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

In most cases, what do you need to to transform HTML code into a static React component?

A
  1. Return the HTML code in render.
  2. Replace class attribute name to className (because class is a reserved word in JavaScript).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the directory node_modules/?

A

It contains all the dependencies that the package manager loads based on the dependencies list defined in the package.json file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the directory public/?

A
  • Public root of the site.
  • Files in there are accessible to anyone on the web.
  • Good place to keep static files and assets that are not being managed in the src/ directory.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the src/ directory?

A

The application code!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Where does the browser look for the initial instructions to render the React app?

A

public/index.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Does the public/index.html file has to be blank? Why not?

A

No: you can add whatever static design frame and elements around the React element, and know that the app will appear inside that element when JavaScript executes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is src/index.js?

A

It is the file where React looks for initial instructions to build UI inside the root element defined in public/index.html.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are the two different ways to import modules, assuming Webpack is used?

A
  • Modules defined in package.json and installed can be imported by name ==> e.g. import {Module} from ‘module’;
  • Modules that are not package.json can still be imported by specifying a path to the file where those modules are defined ==> e.g. import {Module} from ‘path/to/module’;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are the arguments of the render() function within src/index.js?

A
  1. A React component to render: the ‘App’ component from src/app.js
  2. A DOM node to serve as the render container, that is, the root element.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Why can we use HTML and JSX expressions in a React app JavaScript file?

A

Because the JSX interpreter will compile the JSX tags and HTML tags into calls to React.createElement(). Incidently, the React module has to be imported even if not seemingly used.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the component < App/ >?

A
  • It is the first component the React app will call in index.js.
  • It serves as the container for rendering all the other components in the app.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are all components expected to do?

A

All components are expected to define a function called render() that returns some DOM elements.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Why are curly brackets special inside JSX tags?

A

They indicate that the code inside the curly brackets is JavaScript. It can be used to print the evaluated value of a JavaScript expression in the generated markup.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What cannot be put inside curly brackets inside JSX tags?

A

Statements CANNOT be within these curly brackets, but any JavaScript expression can be.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How to run a React app in development?

A

$ npm start

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What does $ npm test does?

A

It launches a test runner (i.e. Jest) watching changes to the app and trying to run related tests.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What does $ npm run build does?

A

It packages the app for a production deployment, at /build/static/js/.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How does React handles non-JavaScript assets?

A

Webpack loaders (which create-react-app is using behind the scenes to build the app) let you load them directly in Javascript through the module system if files are included in the ‘src’ directory.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is a SPA (Single Page Application)?

A

A SPA website usually loads once, then rewrites sections of a page rather than loading entire new pages from a server.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What are React components?

A
  • Conceptually, components are like JavaScript functions.
  • They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.
  • Components are stateful and reusable.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What are Web components?

A
  • Reusable page elements that encapsulate pieces of functionality.
  • Examples:
    • Search input that offers live previews of search results.
    • Button that shows a tooltip on hover.
  • They are distinct and complementary to React components.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is JSX?

A
  • It is a templating language combining HTML and JavaScript into a single file.
  • It is mostly a syntactic convenience for building up JavaScript objects that describe DOM elements.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What is the rendering limitation of SPAs?

A
  • The client-side rendering that SPAs do means delayed rendering and delivering more JavaScript to the client.
  • This is a limitation that all JavaScript frameworks have.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What is the solution to the limitation of SPAs?

A

Frameworks such as React, Ember and Angular 2 are creating server-side rendering engines in Nodejs that can pre-render the app as static HTML, so that the browser has HTML to read immediately on page load.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What is the alternative to declaring a variable at the top of a file?

A

Make use of constructor function to declare the intitial state of a component:

import React from 'react';

class ComponentName extends React.Component { constructor(props) { super(props); this.state = { [var]: [expression] }; } render() { ... } }}

export default ComponentName;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What are props?

A

Props are arbitrary inputs accepted by components.

  • For components created as objects: props are a property of this.
  • For components created as functions, props are a function parameter.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

How to pass an input as prop to a component?

A

Component some_prop=input / >

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What care should be taken when accessing props within components?

A

Only access props (e.g. this.props) to read values. Never modify props inside components.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Components always need to have one top-level element. How to make sure they do?

A
  1. Add a single wrapper element: < div > … [your_elements] … < /div >
  2. Nest one of the top-level elements inside the other.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What is the basic structure of a Reat component?

A

import React from ‘react’;

class ComponentName extends React.Component {
 render() {
 return (
 [... some elements defined with JSX ...]
 );
 }
}
export default ComponentName;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What is the scope of state?

A

state is a private property of components. Only the corresponding component can read it and change it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What is super(props)?

A

It is a JavaScript expression used to call functions on a parent’s object within a constructor function. It runs the constructor function of the parent component. props is passed along to make sure super() has access to the same arguments as the overwriting constructor.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

How can a component share information about its state?

A

Pass the state explicitly via props in the call to an other component.

36
Q

How to handle the different stages of component’s life in the DOM?

A
  • When a component’s output is first inserted into the DOM it will trigger a hook called componentDidMount().
  • When it’s removed from the DOM it will trigger one called componentWillUnmount().
  • These hooks are on the same level as render() and return(), and between them.
37
Q

Where to store variables set within hooks?

A

They should be stored on the this object or on a variable initialized at the top of a file. Only variables used in render() should be stored in state.

38
Q

How to trigger React to update?

A

Use the setState() method within a function inside a component:

class ComponentName extends React.Component {
 constructor(props) {
 super(props);
 this.state = {
 [var]: [expression]
 };
 }
 updateFunc() {
 this.setState({
 [var]: [expression]
 });
 }
 render() { ... 
 }
}
39
Q

how to refer to props or previous state when using setState?

A

Use a second form of setState that accepts a function as an argument, rather than directly passing the state (because value of state and prop may be unpredictable due to React asynchronous nature):

updateFunc() {

this.setState(function (prevState, props) {

return {

};

});

}

40
Q

What is the basic structure to handle events in React?

A
class MyComponent extends React.Component {
 constructor(props) {
 super(props);
 this.handleClick = this.handleClick.bind(this);
 }
 handleClick(event) {
 console.log(this);
 }
 render() {
 return (
 [button onclick={this.handleClick}]
 Click me

[/button]
);
}
}

41
Q

Why do we need to use a constructor to bind an event to this to handle events?

A

Because the value of this is not bound to the object where the function was originally defined. it is a common pattern when you define a class, and need to preserve reference to this inside its class functions after they are passed around to be executed as callbacks outside the orginal class context.

42
Q

What does it mean that React has a unidirectional data flow?

A

Apps are organized as a series of nested components. These components are functional in nature: they receive information through the props attribute, and pass information via their return values. Data is passed down from components to their children.

43
Q

Should components try to read or modify the DOM directly?

A

No, if you find yourself writing selectors to access elements on the page, then there is something wrong.

44
Q

How can a child element trigger a change reflected in a parent component?

A

The parent component should pass one of its own functions as a callback in a prop when calling the child component.

45
Q

What is the right place of an element of state if two or more components need to share access to it?

A

The right place of the element of state is in a common ancestor component.

46
Q

What is the routing limitation of SPAs?

A

As the application is contained in a single page, it cannot rely on the browser’s forward/back buttons.

47
Q

Add dependencies to package.json, either or both to production and development/test.

A
  • Production: $ npm install [package] –save
  • Development/test: $ npm install [package] –save-dev
48
Q

What is the role of React Router?

A

React Router fixes the routing limitation of PSAs. It allows the application to navigate between different components, changing the browser URL, modifying the browser history, and keeping the UI state in sync.

49
Q

What are the components on which the React Router API is based?

A
  1. Router: keeps the UI in sync with the URL.
  2. Link: renders a navigation link to change the location.
  3. Route: renders a UI component depending on the URL.
50
Q

What are the two router implementations and their URL formats?

A
  • BrowserRouter: using the HTML5 History API.
    • import { BrowserRouter } from ‘react-router-dom’;
    • http://localhost:3000/route/subroute
  • HashRouter: using the hash portion which sets or returns the anchor part of the URL.
    • import { HashRouter } from ‘react-router-dom’;​
    • http://localhost:3000/#/route/subroute
51
Q

How many child elements a router component can have?

A

Only one child component.

52
Q

What is the main job of the Router component?

A

The main job of a Router component is to create a history object to keep track of the location (URL). When the location changes because of a navigation action, the child component is re-rendered.

53
Q

How to use the Link component?

A

[Link to=”route”] text [/Link]

54
Q

Where should the route components be defined?

A

The route components can be placed anywhere inside of the router, and the associated component will be rendered in that place, just like any other component.

55
Q

What is the different between using the Link component and directly using the [a href=”route”] element?

A

The Link components allow to change the URL without refreshing the page, which is not the case when using directly the [a] tag.

56
Q

What does it mean that routes are inclusive?

A

More than one [Route] component can match a URL path and render at the same time.

57
Q

What is the basic format of a route component? What does it do?

A
  • Format: [Route exact path=”/” component={MyComponent}]
  • The matching logic uses the path-to-regexp library: possibility to display different components just by declaring that they belong to the same (or similar) path.
58
Q

What is the use of the exact property for route components?

A

Renders the component only if the defined path matches the URL path exactly.

59
Q

What is the use of the [Switch] component?

A

Make the path matching exclusive rather than inclusive: it renders only the first route that matches the location.

60
Q

How to use the Switch components?

A

Insert Route components as child elements of the Switch component. Note that it is necessary to specify the exact property for the “/” path.

61
Q

How to handle a non-existent path?

A

Within a Switch component, use a [Redirect to=”path” /] component. This component will navigate to a new location overriding the current one in the history stack.

62
Q

What are the 3 properties passed as parameters when a component is rendered by the router?

A
  • match
  • location
  • history
63
Q

What are the properties of the match object created during a match between the router’s path and the URL location?

A
  • params: key/value pairs parsed from the URL.
  • isExact: true if the entire URL was matched.
  • path: path pattern used to match.
  • url: matched portion of the URL.
64
Q

How to define what is rendered by a Route component?

A

Use one of the 3 following properties:

  • component: render a component.
  • render: renders an element or component.
  • children: renders an element or component regardless of whether the path is matched or not.
65
Q

How to pass a prop to a component being rendered by React Router?

A
< Route 
    path="/some_path" 
    render={(props) => < Component {...props} myProp={myValue} / >}
/ >
66
Q

What is the ComponentWillMount life cycle method? What is its purpose?

A
  • Only called one time before the initial render().
  • Component does not have accees to the Natve UI (DOM, etc…) and children refs.
  • Opportunity to handle configuration, update our state and prepare for the first render().
  • Possible to safely query this.props and this.state knowing with certainty they are the current value.
67
Q

What is the best way to handle a Promise?

A
myPromise.then(function() {
   // Handle success
   // Some error may happen during handling of success
}).catch(function() {
   // Handle error
});
68
Q

What is Local Storage?

A

Local Storage is a Web API native to modern web browsers. It allows websites/apps to store simple and limited data in the browser, making that data available in future browser sessions.

69
Q

How to store and retrieve items from local storage?

A
// setter
localStorage.setItem('myData', data);
// getter
localStorage.getItem('myData');
70
Q

How to use local storage as cache? Give an example of a search function with the native fetch API.

A
class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = { hits: null };
  }

  onSearch = (e) => {
    e.preventDefault();
    const { value } = this.input;

    if (value === '') {
      return;
    }
const cachedHits = localStorage.getItem(value);
if (cachedHits) {
  this.setState({ hits: JSON.parse(cachedHits) });
  return;
} ~~~

fetch('https://example.com/api/v1/search?query=' + value)
  .then(response => response.json())
  .then(result => this.onSetResult(result, value));   }

onSetResult = (result, key) => {
localStorage.setItem(key, JSON.stringify(result.hits));
this.setState({ hits: result.hits });
}
render() {…}
}
~~~

71
Q

What to use if you want the cache to be emptied when closing the browser?

A

Use sessionStorage instead of localStorage. Setter and getter are the same as localStorage.

72
Q

What is the purpose of withRouter?

A
  • When a component is rendered by React Router via component prop to a Route, that component is passed 3 different props: location, match and history.
  • If we render it ourselves (like < Component / > ), then we do not have access to these Router props. By adding the HOC withRouter in export default withRouter(Component), that takes care of this issue.
73
Q

What are the inputs of the WindowOrWorkerGlobalScope.fetch() method?

A
  • input: either a USVString containing a direct URL or a Request object.
  • init (optional): an object containing any custom settings that should be applied to the request, such as: method, headers, body…
74
Q

What is the return value of the WindowOrWorkerGlobalScope.fetch() method?

A

A Promise that resolves to a Response object.

75
Q

What are the properties of the Response object?

A
  • headers.
  • ok: boolean for success/failure.
  • redirected: boolean for whether or not the response’s URL list has more than one entry.
  • status: code.
  • statusText.
  • type: e.g. basic, cors.
  • url: final URL.
  • useFinalURL: boolean for whether this is the final URL of the response.
76
Q

What does Response.json() do?

A

The json() method of the Body class (inplemented by Response) takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON.

77
Q

What does Object.assign() do? Give its syntax.

A

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object. The target object can be {}.

Syntax: const targetObject = Object.assign(target, …sources)

78
Q
A
79
Q

What does Promise.reject(reason) does?

A

It returns a Promise object that is rejected with the given reason. For debugging purposes and selective error catchng, it is useful to make reason an instance of Error.

80
Q

Give an example of Promise.reject().

A
Promise.reject(new Error('fail'))     
    .then(function() { 
        // not called 
    }, function(error) { 
        console.log(error); // Stacktrace 
    } 
);
81
Q

What is the flexbox algorithm?

A

An algorithm providing consistent layout on different screen sizes.

82
Q

What are the primary properties of flexboxes?

A
  • flexDirection.
  • alignItems.
  • justifyContent.
83
Q

What are the possible values of the flexDirection property of flexbox?

A

Determines the primary axis of a component’s layout: should the children be organized:

  • horizontally (row)
  • or vertically (column) ==> default.
84
Q

What are the possible values of the justifyContent property of flexbox?

A

Determines the distribution of children along the primary axis (X).

Positional alignments:

  • flex-start: aligns items at the beginning of the container ==> default.
  • center: aligns items at the center of the container.
  • flex-end: aligns items at the end of the container.

Distributed alignments:

  • space-around: evenly distributes items along the main axis such that all items have equal space around them.
  • space-between: evenly distributes items along the main axis such that the first item aligns at the start and the final item aligns at the end.
85
Q

What are the possible values of the alignItems property of flexbox?

A

Determines the alignment of children along the secondary axis (Y). If the primary axis is row, then the secondary is column, and vice versa.

Positional alignments:

  • flex-start: aligns items at the beginning of the container ==> default.
  • center: aligns items at the center of the container.
  • flex-end: aligns items at the end of the container.

Distributed alignments:

  • stretch: stretches the items to fill the container ==> default.
  • baseline: aligns the items so that their baselines align.
86
Q

How does a tradiotional website loads assets like CSS, images and web fonts?

A

A traditional website loads assets like CSS, images and web fonts from remote files based on urls in src attributes in HTML tags or stylesheet rules.