React II Flashcards
What are the recommended ways for static type checking?
Normally we use PropTypes library (React.PropTypes moved to a prop-types package since React v15.5) for type checking in the React applications. For large code bases, it is recommended to use static type checkers such as Flow or TypeScript, that perform type checking at compile time and provide auto-completion features.
What is the use of react-dom package?
The react-dom package provides DOM-specific methods that can be used at the top level of your app. Most of the components are not required to use this module. Some of the methods of this package are:
render() hydrate() unmountComponentAtNode() findDOMNode() createPortal()
What is ReactDOMServer?
The ReactDOMServer object enables you to render components to static markup (typically used on node server). This object is mainly used for server-side rendering (SSR). The following methods can be used in both the server and browser environments:
renderToString() renderToStaticMarkup()
For example, you generally run a Node-based web server like Express, Hapi, or Koa, and you call renderToString to render your root component to a string, which you then send as response.
How to use innerHTML in React?
The dangerouslySetInnerHTML attribute is React’s replacement for using innerHTML in the browser DOM. Just like innerHTML, it is risky to use this attribute considering cross-site scripting (XSS) attacks. You just need to pass a __html object as key and HTML text as value.
How to use styles in React?
The style attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM style JavaScript property, is more efficient, and prevents XSS security holes.
const divStyle = {
color: “blue”,
backgroundImage: “url(“ + imgUrl + “)”,
};
function HelloWorldComponent() {
return <div style={divStyle}>Hello World!</div>;
}
How events are different in React?
Handling events in React elements has some syntactic differences:
React event handlers are named using camelCase, rather than lowercase. With JSX you pass a function as the event handler, rather than a string.
What is the impact of indexes as keys?
Keys should be stable, predictable, and unique so that React can keep track of elements.
In the below code snippet each element’s key will be based on ordering, rather than tied to the data that is being represented. This limits the optimizations that React can do and creates confusing bugs in the application.
{
todos.map((todo, index) => <Todo {…todo} key={index} />);
}
If you use element data for unique key, assuming todo.id is unique to this list and stable, React would be able to reorder elements without needing to reevaluate them as much.
{
todos.map((todo) => <Todo {…todo} key={todo.id} />);
}
How do you conditionally render components?
In some cases you want to render different components depending on some state. JSX does not render false or undefined, so you can use conditional short-circuiting to render a given part of your component only if a certain condition is true.
const MyComponent = ({ name, address }) => (
<div>
<h2>{name}</h2>
{address && <p>{address}</p>}
</div>
);
If you need an if-else condition then use ternary operator.
const MyComponent = ({ name, address }) => (
<div>
<h2>{name}</h2>
{address ? <p>{address}</p> : <p>{"Address is not available"}</p>}
</div>
);
Why we need to be careful when spreading props on DOM elements?
When we spread props we run into the risk of adding unknown HTML attributes, which is a bad practice. Instead we can use prop destructuring with …rest operator, so it will add only required props.
For example,
const ComponentA = () => (
<ComponentB isDisplay={true} className={“componentStyle”} />
);
const ComponentB = ({ isDisplay, …domProps }) => (
<div {…domProps}>{“ComponentB”}</div>
);
How do you memoize a component?
There are memoize libraries available which can be used on function components.
For example moize library can memoize the component in another component.
import moize from “moize”;
import Component from “./components/Component”; // this module exports a non-memoized component
const MemoizedFoo = moize.react(Component);
const Consumer = () => {
<div>
{"I will memoize the following entry:"}
<MemoizedFoo></MemoizedFoo>
</div>
;
};
Update: Since React v16.6.0, we have a React.memo. It provides a higher order component which memoizes component unless the props change. To use it, simply wrap the component using React.memo before you use it.
const MemoComponent = React.memo(function MemoComponent(props) {
/* render using props */
});
OR;
export default React.memo(MyFunctionComponent);
How you implement Server Side Rendering or SSR?
React is already equipped to handle rendering on Node servers. A special version of the DOM renderer is available, which follows the same pattern as on the client side.
import ReactDOMServer from “react-dom/server”;
import App from “./App”;
ReactDOMServer.renderToString(<App></App>);
This method will output the regular HTML as a string, which can be then placed inside a page body as part of the server response. On the client side, React detects the pre-rendered content and seamlessly picks up where it left off.
How to enable production mode in React?
You should use Webpack’s DefinePlugin method to set NODE_ENV to production, by which it strip out things like propType validation and extra warnings. Apart from this, if you minify the code, for example, Uglify’s dead-code elimination to strip out development only code and comments, it will drastically reduce the size of your bundle.
Do Hooks replace render props and higher order components?
Both render props and higher-order components render only a single child but in most of the cases Hooks are a simpler way to serve this by reducing nesting in your tree.
What is a switching component?
A switching component is a component that renders one of many components. We need to use object to map prop values to components.
What are React Mixins?
Mixins are a way to totally separate components to have a common functionality. Mixins should not be used and can be replaced with higher-order components or decorators.
One of the most commonly used mixins is PureRenderMixin. You might be using it in some components to prevent unnecessary re-renders when the props and state are shallowly equal to the previous props and state:
const PureRenderMixin = require(“react-addons-pure-render-mixin”);
const Button = React.createClass({
mixins: [PureRenderMixin],
// …
});
What are the Pointer Events supported in React?
Pointer Events provide a unified way of handling all input events. In the old days we had a mouse and respective event listeners to handle them but nowadays we have many devices which don’t correlate to having a mouse, like phones with touch surface or pens. We need to remember that these events will only work in browsers that support the Pointer Events specification.
The following event types are now available in React DOM:
onPointerDown onPointerMove onPointerUp onPointerCancel onGotPointerCapture onLostPointerCapture onPointerEnter onPointerLeave onPointerOver onPointerOut
Why should component names start with capital letter?
If you are rendering your component using JSX, the name of that component has to begin with a capital letter otherwise React will throw an error as an unrecognized tag. This convention is because only HTML elements and SVG tags can begin with a lowercase letter.
function SomeComponent {
// Code goes here
}
You can define function component whose name starts with lowercase letter, but when it’s imported it should have a capital letter. Here lowercase is fine:
function myComponent {
render() {
return <div />;
}
}
export default myComponent;
While when imported in another file it should start with capital letter:
import MyComponent from “./myComponent”;
Are custom DOM attributes supported in React v16?
Yes. In the past, React used to ignore unknown DOM attributes. If you wrote JSX with an attribute that React doesn’t recognize, React would just skip it.
For example, let’s take a look at the below attribute:
<div mycustomattribute={“something”} />
Would render an empty div to the DOM with React v15:
<div></div>
In React v16 any unknown attributes will end up in the DOM:
<div></div>
This is useful for supplying browser-specific non-standard attributes, trying new DOM APIs, and integrating with opinionated third-party libraries.
How to loop inside JSX?
You can simply use Array.prototype.map with ES6 arrow function syntax.
For example, the items array of objects is mapped into an array of components:
<tbody>
{items.map((item) => (
<SomeComponent key={item.id} name={item.name} />
))}
</tbody>
But you can’t iterate using for loop:
<tbody>
for (let i = 0; i < items.length; i++) {
<SomeComponent key={items[i].id} name={items[i].name} />
}
</tbody>
This is because JSX tags are transpiled into function calls, and you can’t use statements inside expressions. This may change thanks to do expressions which are stage 1 proposal.
How do you access props in attribute quotes?
React (or JSX) doesn’t support variable interpolation inside an attribute value. The below representation won’t work:
<img></img>
But you can put any JS expression inside curly braces as the entire attribute value. So the below expression works:
<img className=”image” src={“images/” + this.props.image} />
Using template strings will also work:
<img className=”image” src={images/${this.props.image}
} />
What is React proptype array with shape?
If you want to pass an array of objects to a component with a particular shape then use React.PropTypes.shape() as an argument to React.PropTypes.arrayOf().
ReactComponent.propTypes = {
arrayWithShape: React.PropTypes.arrayOf(
React.PropTypes.shape({
color: React.PropTypes.string.isRequired,
fontSize: React.PropTypes.number.isRequired,
})
).isRequired,
};
How to conditionally apply class attributes?
You shouldn’t use curly braces inside quotes because it is going to be evaluated as a string.
<div>
Instead you need to move curly braces outside (don't forget to include spaces between class names):
<div className={'btn-panel ' + (this.props.visible ? 'show' : 'hidden')}>
Template strings will also work:
<div className={`btn-panel ${this.props.visible ? 'show' : 'hidden'}`}>
</div>
What is the difference between React and ReactDOM?
The react package contains React.createElement(), React.Component, React.Children, and other helpers related to elements and component classes. You can think of these as the isomorphic or universal helpers that you need to build components. The react-dom package contains ReactDOM.render(), and in react-dom/server we have server-side rendering support with ReactDOMServer.renderToString() and ReactDOMServer.renderToStaticMarkup().
Why ReactDOM is separated from React?
The React team worked on extracting all DOM-related features into a separate library called ReactDOM. React v0.14 is the first release in which the libraries are split. By looking at some of the packages, react-native, react-art, react-canvas, and react-three, it has become clear that the beauty and essence of React has nothing to do with browsers or the DOM.
To build more environments that React can render to, React team planned to split the main React package into two: react and react-dom. This paves the way to writing components that can be shared between the web version of React and React Native.
How to use React label element?
If you try to render a <label> element bound to a text input using the standard for attribute, then it produces HTML missing that attribute and prints a warning to the console.</label>
<label for={‘user’}>{‘User’}</label>
<input type={‘text’} id={‘user’} />
Since for is a reserved keyword in JavaScript, use htmlFor instead.
<label htmlFor={‘user’}>{‘User’}</label>
<input type={‘text’} id={‘user’} />
How to combine multiple inline style objects?
You can use spread operator in regular React:
<button style={{ …styles.panel.button, …styles.panel.submitButton }}>
{“Submit”}
</button>
If you’re using React Native then you can use the array notation:
<button style={[styles.panel.button, styles.panel.submitButton]}>
{“Submit”}
</button>
How to re-render the view when the browser is resized?
You can use the useState hook to manage the width and height state variables, and the useEffect hook to add and remove the resize event listener. The [] dependency array passed to useEffect ensures that the effect only runs once (on mount) and not on every re-render.
import React, { useState, useEffect } from “react”;
function WindowDimensions() {
const [dimensions, setDimensions] = useState({
width: window.innerWidth,
height: window.innerHeight,
});
useEffect(() => {
function handleResize() {
setDimensions({
width: window.innerWidth,
height: window.innerHeight,
});
}
window.addEventListener(“resize”, handleResize);
return () => window.removeEventListener(“resize”, handleResize);
}, []);
return (
<span>
{dimensions.width} x {dimensions.height}
</span>
);
}
How to pretty print JSON with React?
We can use <pre> tag so that the formatting of the JSON.stringify() is retained:
const data = { name: “John”, age: 42 };
function User {
return <pre>{JSON.stringify(data, null, 2)}</pre>;
}
const container = createRoot(document.getElementById(“container”));
container.render(<User></User>);
Why you can’t update props in React?
The React philosophy is that props should be immutable(read only) and top-down. This means that a parent can send any prop values to a child, but the child can’t modify received props.
How to focus an input element on page load?
You need to use useEffect hook to set focus on input field during page load time for functional component.
import React, { useEffect, useRef } from “react”;
const App = () => {
const inputElRef = useRef(null);
useEffect(() => {
inputElRef.current.focus();
}, []);
return (
<div>
<input defaultValue={“Won’t focus”} />
<input ref={inputElRef} defaultValue={“Will focus”} />
</div>
);
};
ReactDOM.render(<App></App>, document.getElementById(“app”));
What are the exceptions on React component naming?
The component names should start with an uppercase letter but there are few exceptions to this convention. The lowercase tag names with a dot (property accessors) are still considered as valid component names. For example, the below tag can be compiled to a valid component,
What is React Router?
React Router is a powerful routing library built on top of React that helps you add new screens and flows to your application incredibly quickly, all while keeping the URL in sync with what’s being displayed on the page.
How React Router is different from history library?
React Router is a wrapper around the history library which handles interaction with the browser’s window.history with its browser and hash histories. It also provides memory history which is useful for environments that don’t have global history, such as mobile app development (React Native) and unit testing with Node.
What are the <Router> components of React Router v6?</Router>
React Router v6 provides below 4 <Router> components:</Router>
<BrowserRouter>:Uses the HTML5 history API for standard web apps. <HashRouter>:Uses hash-based routing for static servers. <MemoryRouter>:Uses in-memory routing for testing and non-browser environments. <StaticRouter>:Provides static routing for server-side rendering (SSR).
The above components will create browser, hash, memory and static history instances. React Router v6 makes the properties and methods of the history instance associated with your router available through the context in the router object.
What is the purpose of push() and replace() methods of history?
A history instance has two methods for navigation purpose.
push() replace()
If you think of the history as an array of visited locations, push() will add a new location to the array and replace() will replace the current location in the array with the new one.
How do you programmatically navigate using React Router v4?
There are three different ways to achieve programmatic routing/navigation within components.
Using the withRouter() higher-order function: The withRouter() higher-order function will inject the history object as a prop of the component. This object provides push() and replace() methods to avoid the usage of context. import { withRouter } from "react-router-dom"; // this also works with 'react-router-native' const Button = withRouter(({ history }) => ( <button type="button" onClick={() => { history.push("/new-location"); }} > {"Click Me!"} </button> ));
Using <Route> component and render props pattern:</Route>
The <Route> component passes the same props as withRouter(), so you will be able to access the history methods through the history prop.</Route>
import { Route } from “react-router-dom”;
const Button = () => (
<Route
render={({ history }) => (
<button
type=”button”
onClick={() => {
history.push(“/new-location”);
}}
>
{“Click Me!”}
</button>
)}
/>
);
Using context:
This option is not recommended and treated as unstable API.
const Button = (props, context) => (
<button
type=”button”
onClick={() => {
context.history.push(“/new-location”);
}}
>
{“Click Me!”}
</button>
);
Button.contextTypes = {
history: React.PropTypes.shape({
push: React.PropTypes.func.isRequired,
}),
};
How to get query parameters in React Router v4?
The ability to parse query strings was taken out of React Router v4 because there have been user requests over the years to support different implementation. So the decision has been given to users to choose the implementation they like. The recommended approach is to use query strings library.
const queryString = require(“query-string”);
const parsed = queryString.parse(props.location.search);
You can also use URLSearchParams if you want something native:
const params = new URLSearchParams(props.location.search);
const foo = params.get(“name”);
Why you get “Router may have only one child element” warning?
You have to wrap your Route’s in a <Switch> block because <Switch> is unique in that it renders a route exclusively.</Switch></Switch>
At first you need to add Switch to your imports:
import { Switch, Router, Route } from “react-router”;
Then define the routes within <Switch> block:</Switch>
<Router>
<Switch>
<Route {/* ... */} />
<Route {/* ... */} />
</Switch>
</Router>
How to pass params to history.push method in React Router v4?
While navigating you can pass props to the history object:
this.props.history.push({
pathname: “/template”,
search: “?name=sudheer”,
state: { detail: response.data },
});
The search property is used to pass query params in push() method.
How to implement default or NotFound page?
A <Switch> renders the first child <Route> that matches. A <Route> with no path always matches. So you just need to simply drop path attribute as below</Route></Route></Switch>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/user" component={User} />
<Route component={NotFound} />
</Switch>
How to get history on React Router v4?
Below are the list of steps to get history object on React Router v4,
Create a module that exports a history object and import this module across the project. For example, create history.js file: import { createBrowserHistory } from "history"; export default createBrowserHistory({ /* pass a configuration object here if needed */ });
You should use the <Router> component instead of built-in routers. Import the above history.js inside index.js file:</Router>
import { Router } from “react-router-dom”;
import history from “./history”;
import App from “./App”;
ReactDOM.render(
<Router history={history}>
<App></App>
</Router>,
holder
);
You can also use push method of history object similar to built-in history object:
// some-other-file.js
import history from “./history”;
history.push(“/go-here”);
How to perform automatic redirect after login?
The react-router package provides <Redirect> component in React Router. Rendering a <Redirect> will navigate to a new location. Like server-side redirects, the new location will override the current location in the history stack.</Redirect></Redirect>
import { Redirect } from “react-router”;
export default function Login {
if (this.state.isLoggedIn === true) {
return <Redirect></Redirect>;
} else {
return <div>{“Login Please”}</div>;
}
}