81. 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.
For example, a switching component to display different pages based on `page` prop:
```jsx harmony
import HomePage from './HomePage'
import AboutPage from './AboutPage'
import ServicesPage from './ServicesPage'
import ContactPage from './ContactPage'
const PAGES = {
home: HomePage,
about: AboutPage,
services: ServicesPage,
contact: ContactPage
}
const Page = (props) => {
const Handler = PAGES[props.page] || ContactPage
return <Handler {...props} />
}
// The keys of the PAGES object can be used in the prop types to catch dev-time errors.
Page.propTypes = {
page: PropTypes.oneOf(Object.keys(PAGES)).isRequired
}
```
82. Why we need to pass a function to setState()?
The reason behind for this is that `setState()` is an asynchronous operation. React batches state changes for performance reasons, so the state may not change immediately after `setState()` is called. That means you should not rely on the current state when calling `setState()` since you can't be sure what that state will be. The solution is to pass a function to `setState()`, with the previous state as an argument. By doing this you can avoid issues with the user getting the old state value on access due to the asynchronous nature of `setState()`.
Let's say the initial count value is zero. After three consecutive increment operations, the value is going to be incremented only by one.
```javascript
// assuming this.state.count === 0
this.setState({ count: this.state.count + 1 })
this.setState({ count: this.state.count + 1 })
this.setState({ count: this.state.count + 1 })
// this.state.count === 1, not 3
```
If we pass a function to `setState()`, the count gets incremented correctly.
```javascript
this.setState((prevState, props) => ({
count: prevState.count + props.increment
}))
// this.state.count === 3 as expected
```
83. What is strict mode in React?
`React.StrictMode` is an useful component for highlighting potential problems in an application. Just like `<Fragment>`, `<StrictMode>` does not render any extra DOM elements. It activates additional checks and warnings for its descendants. These checks apply for *development mode* only.
```jsx harmony
import React from 'react'
function ExampleApplication() {
return (
<div>
<Header />
<React.StrictMode>
<div>
<ComponentOne />
<ComponentTwo />
</div>
</React.StrictMode>
<Footer />
</div>
)
}
```
In the example above, the *strict mode* checks apply to `<ComponentOne>` and `<ComponentTwo>` components only.
84. 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:
```javascript
const PureRenderMixin = require('react-addons-pure-render-mixin')
const Button = React.createClass({
mixins: [PureRenderMixin],
// ...
})
````
<!-- TODO: mixins are deprecated -->
85. Why is `isMounted()` an anti-pattern and what is the proper solution?
The primary use case for `isMounted()` is to avoid calling `setState()` after a component has been unmounted, because it will emit a warning.
```javascript
if (this.isMounted()) {
this.setState({...})
}
```
Checking `isMounted()` before calling `setState()` does eliminate the warning, but it also defeats the purpose of the warning. Using `isMounted()` is a code smell because the only reason you would check is because you think you might be holding a reference after the component has unmounted.
An optimal solution would be to find places where `setState()` might be called after a component has unmounted, and fix them. Such situations most commonly occur due to callbacks, when a component is waiting for some data and gets unmounted before the data arrives. Ideally, any callbacks should be canceled in `componentWillUnmount()`, prior to unmounting.
86. 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*:
1. `onPointerDown`
2. `onPointerMove`
3. `onPointerUp`
4. `onPointerCancel`
5. `onGotPointerCapture`
6. `onLostPointerCaptur`
7. `onPointerEnter`
8. `onPointerLeave`
9. `onPointerOver`
10. `onPointerOut`
87. 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 unrecognized tag. This convention is because only HTML elements and SVG tags can begin with a lowercase letter.
```jsx harmony
class SomeComponent extends Component {
// Code goes here
}
```
You can define component class which name starts with lowercase letter, but when it's imported it should have capital letter. Here lowercase is fine:
```jsx harmony
class myComponent extends Component {
render() {
return <div />
}
}
export default myComponent
```
While when imported in another file it should start with capital letter:
```jsx harmony
import MyComponent from './MyComponent'
```
88. 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, this:
```jsx harmony
<div mycustomattribute={'something'} />
```
Would render an empty div to the DOM with React v15:
```html
<div />
```
In React v16 any unknown attributes will end up in the DOM:
```html
<div mycustomattribute='something' />
```
This is useful for supplying browser-specific non-standard attributes, trying new DOM APIs, and integrating with opinionated third-party libraries.
89. What is the difference between constructor and getInitialState?
You should initialize state in the constructor when using ES6 classes, and `getInitialState()` method when using `React.createClass()`.
Using ES6 classes:
```javascript
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = { /* initial state */ }
}
}
```
Using `React.createClass()`:
```javascript
const MyComponent = React.createClass({
getInitialState() {
return { /* initial state */ }
}
})
```
**Note:** `React.createClass()` is deprecated and removed in React v16. Use plain JavaScript classes instead.
90. Can you force a component to re-render without calling setState?
By default, when your component's state or props change, your component will re-render. If your `render()` method depends on some other data, you can tell React that the component needs re-rendering by calling `forceUpdate()`.
```javascript
component.forceUpdate(callback)
```
It is recommended to avoid all uses of `forceUpdate()` and only read from `this.props` and `this.state` in `render()`.
91. What is the difference between `super()` and `super(props)` in React using ES6 classes?
When you want to access `this.props` in `constructor()` then you should pass props to `super()` method.
Using `super(props)`:
```javascript
class MyComponent extends React.Component {
constructor(props) {
super(props)
console.log(this.props) // { name: 'John', ... }
}
}
```
Using `super()`:
```javascript
class MyComponent extends React.Component {
constructor(props) {
super()
console.log(this.props) // undefined
}
}
```
Outside `constructor()` both will display same value for `this.props`.
92. 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:
```jsx harmony
<tbody>
{items.map(item => <SomeComponent key={item.id} name={item.name} />)}
</tbody>
```
You can't iterate using `for` loop:
```jsx harmony
<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*.
93. 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:
```jsx harmony
<img className='image' src='images/{this.props.image}' />
```
But you can put any JS expression inside curly braces as the entire attribute value. So the below expression works:
```jsx harmony
<img className='image' src={'images/' + this.props.image} />
```
Using *template strings* will also work:
```jsx harmony
<img className='image' src={`images/${this.props.image}`} />
```
94. 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()`.
```javascript
ReactComponent.propTypes = {
arrayWithShape: React.PropTypes.arrayOf(React.PropTypes.shape({
color: React.PropTypes.string.isRequired,
fontSize: React.PropTypes.number.isRequired
})).isRequired
}
```
95. How to conditionally apply class attributes?
You shouldn't use curly braces inside quotes because it is going to be evaluated as a string.
```jsx harmony
<div className="btn-panel {this.props.visible ? 'show' : 'hidden'}">
```
Instead you need to move curly braces outside (don't forget to include spaces between class names):
```jsx harmony
<div className={'btn-panel ' + (this.props.visible ? 'show' : 'hidden')}>
```
*Template strings* will also work:
```jsx harmony
<div className={`btn-panel ${this.props.visible ? 'show' : 'hidden'}`}>
```
96. 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()`.
97. 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.
98. 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.
```jsx harmony
<label for={'user'}>{'User'}</label>
<input type={'text'} id={'user'} />
```
Since `for` is a reserved keyword in JavaScript, use `htmlFor` instead.
```jsx harmony
<label htmlFor={'user'}>{'User'}</label>
<input type={'text'} id={'user'} />
```
99. How to combine multiple inline style objects?
You can use *spread operator* in regular React:
```jsx harmony
<button style={{...styles.panel.button, ...styles.panel.submitButton}}>{'Submit'}</button>
```
If you're using React Native then you can use the array notation:
```jsx harmony
<button style={[styles.panel.button, styles.panel.submitButton]}>{'Submit'}</button>
```
100. How to re-render the view when the browser is resized?
You can listen to the `resize` event in `componentDidMount()` and then update the dimensions (`width` and `height`). You should remove the listener in `componentWillUnmount()` method.
```javascript
class WindowDimensions extends React.Component {
constructor(props){
super(props);
this.updateDimensions = this.updateDimensions.bind(this);
}
componentWillMount() {
this.updateDimensions()
}
componentDidMount() {
window.addEventListener('resize', this.updateDimensions)
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateDimensions)
}
updateDimensions() {
this.setState({width: window.innerWidth, height: window.innerHeight})
}
render() {
return <span>{this.state.width} x {this.state.height}</span>
}
}
```
101. What is the difference between `setState()` and `replaceState()` methods?
When you use `setState()` the current and previous states are merged. `replaceState()` throws out the current state, and replaces it with only what you provide. Usually `setState()` is used unless you really need to remove all previous keys for some reason. You can also set state to `false`/`null` in `setState()` instead of using `replaceState()`.
102. How to listen to state changes?
The following lifecycle methods will be called when state changes. You can compare provided state and props values with current state and props to determine if something meaningful changed.
```
componentWillUpdate(object nextProps, object nextState)
componentDidUpdate(object prevProps, object prevState)
```
103. What is the recommended approach of removing an array element in React state?
The better approach is to use `Array.prototype.filter()` method.
For example, let's create a `removeItem()` method for updating the state.
```javascript
removeItem(index) {
this.setState({
data: this.state.data.filter((item, i) => i !== index)
})
}
```
104. Is it possible to use React without rendering HTML?
It is possible with latest version (>=16.2). Below are the possible options:
```jsx harmony
render() {
return false
}
```
```jsx harmony
render() {
return null
}
```
```jsx harmony
render() {
return []
}
```
```jsx harmony
render() {
return <React.Fragment></React.Fragment>
}
```
```jsx harmony
render() {
return <></>
}
```
Returning `undefined` won't work.
105. How to pretty print JSON with React?
We can use `<pre>` tag so that the formatting of the `JSON.stringify()` is retained:
```jsx harmony
const data = { name: 'John', age: 42 }
class User extends React.Component {
render() {
return (
<pre>
{JSON.stringify(data, null, 2)}
</pre>
)
}
}
React.render(<User />, document.getElementById('container'))
```
Comments
Post a Comment
please do not enter any spam link in the comment box