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.
tag so that the formatting of the JSON.stringify() is retained: const data = { name: "John", age: 42 }; function User { return{JSON.stringify(data, null, 2)}; } const container = createRoot(document.getElementById("container")); container.render();