106. Why you can't update props in React?
The React philosophy is that props should be *immutable* and *top-down*. This means that a parent can send any prop values to a child, but the child can't modify received props.
107. How to focus an input element on page load?
You can do it by creating *ref* for `input` element and using it in `componentDidMount()`:
```jsx harmony
class App extends React.Component{
componentDidMount() {
this.nameInput.focus()
}
render() {
return (
<div>
<input
defaultValue={'Won\'t focus'}
/>
<input
ref={(input) => this.nameInput = input}
defaultValue={'Will focus'}
/>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'))
```
108. What are the possible ways of updating objects in state?
1. **Calling `setState()` with an object to merge with state:**
* Using `Object.assign()` to create a copy of the object:
```javascript
const user = Object.assign({}, this.state.user, { age: 42 })
this.setState({ user })
```
* Using *spread operator*:
```javascript
const user = { ...this.state.user, age: 42 }
this.setState({ user })
```
2. **Calling `setState()` with a function:**
```javascript
this.setState(prevState => ({
user: {
...prevState.user,
age: 42
}
}))
```
109. Why function is preferred over object for `setState()`?
React may batch multiple `setState()` calls into a single update for performance. Because `this.props` and `this.state` may be updated asynchronously, you should not rely on their values for calculating the next state.
This counter example will fail to update as expected:
```javascript
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
})
```
The preferred approach is to call `setState()` with function rather than object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument.
```javascript
// Correct
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}))
```
110. How can we find the version of React at runtime in the browser?
You can use `React.version` to get the version.
```jsx harmony
const REACT_VERSION = React.version
ReactDOM.render(
<div>{`React version: ${REACT_VERSION}`}</div>,
document.getElementById('app')
)
```
111. What are the approaches to include polyfills in your `create-react-app`?
1. **Manual import from `core-js`:**
Create a file called (something like) `polyfills.js` and import it into root `index.js` file. Run `npm install core-js` or `yarn add core-js` and import your specific required features.
```javascript
import 'core-js/fn/array/find'
import 'core-js/fn/array/includes'
import 'core-js/fn/number/is-nan'
```
2. **Using Polyfill service:**
Use the polyfill.io CDN to retrieve custom, browser-specific polyfills by adding this line to `index.html`:
```html
<script src='https://cdn.polyfill.io/v2/polyfill.min.js?features=default,Array.prototype.includes'></script>
```
In the above script we had to explicitly request the `Array.prototype.includes` feature as it is not included in the default feature set.
112. How to use https instead of http in create-react-app?
You just need to use `HTTPS=true` configuration. You can edit your `package.json` scripts section:
```json
"scripts": {
"start": "set HTTPS=true && react-scripts start"
}
```
or just run `set HTTPS=true && npm start`
113. How to avoid using relative path imports in create-react-app?
Create a file called `.env` in the project root and write the import path:
```
NODE_PATH=src/app
```
After that restart the development server. Now you should be able to import anything inside `src/app` without relative paths.
114. How to add Google Analytics for React Router?
Add a listener on the `history` object to record each page view:
```javascript
history.listen(function (location) {
window.ga('set', 'page', location.pathname + location.search)
window.ga('send', 'pageview', location.pathname + location.search)
})
```
115. How to update a component every second?
You need to use `setInterval()` to trigger the change, but you also need to clear the timer when the component unmounts to prevent errors and memory leaks.
```javascript
componentDidMount() {
this.interval = setInterval(() => this.setState({ time: Date.now() }), 1000)
}
componentWillUnmount() {
clearInterval(this.interval)
}
```
116. How do you apply vendor prefixes to inline styles in React?
React *does not* apply *vendor prefixes* automatically. You need to add vendor prefixes manually.
```jsx harmony
<div style={{
transform: 'rotate(90deg)',
WebkitTransform: 'rotate(90deg)', // note the capital 'W' here
msTransform: 'rotate(90deg)' // 'ms' is the only lowercase vendor prefix
}} />
```
117. How to import and export components using React and ES6?
You should use default for exporting the components
```jsx harmony
import React from 'react'
import User from 'user'
export default class MyProfile extends React.Component {
render(){
return (
<User type="customer">
//...
</User>
)
}
}
```
With the export specifier, the MyProfile is going to be the member and exported to this module and the same can be imported without mentioning the name in other components.
118. What are the exceptions on React component naming?
The component names should start with a uppercase letter but there are few exceptions on 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,
```javascript
render(){
return (
<obj.component /> // `React.createElement(obj.component)`
)
}
```
119. Why is a component constructor called only once?
React's *reconciliation* algorithm assumes that without any information to the contrary, if a custom component appears in the same place on subsequent renders, it's the same component as before, so reuses the previous instance rather than creating a new one.
120. How to define constants in React?
You can use ES7 `static` field to define constant.
```javascript
class MyComponent extends React.Component {
static DEFAULT_PAGINATION = 10
}
```
*Static fields* are part of the *Class Fields* stage 3 proposal.
121. How to programmatically trigger click event in React?
You could use the ref prop to acquire a reference to the underlying `HTMLInputElement` object through a callback, store the reference as a class property, then use that reference to later trigger a click from your event handlers using the `HTMLElement.click` method. This can be done in two steps:
1. Create ref in render method:
```jsx harmony
<input ref={input => this.inputElement = input} />
```
2. Apply click event in your event handler:
```javascript
this.inputElement.click()
```
122. Is it possible to use async/await in plain React?
If you want to use `async`/`await` in React, you will need *Babel* and [transform-async-to-generator](https://babeljs.io/docs/en/babel-plugin-transform-async-to-generator) plugin. React Native ships with Babel and a set of transforms.
123. What are the common folder structures for React?
There are two common practices for React project file structure.
1. **Grouping by features or routes:**
One common way to structure projects is locate CSS, JS, and tests together, grouped by feature or route.
```
common/
├─ Avatar.js
├─ Avatar.css
├─ APIUtils.js
└─ APIUtils.test.js
feed/
├─ index.js
├─ Feed.js
├─ Feed.css
├─ FeedStory.js
├─ FeedStory.test.js
└─ FeedAPI.js
profile/
├─ index.js
├─ Profile.js
├─ ProfileHeader.js
├─ ProfileHeader.css
└─ ProfileAPI.js
```
2. **Grouping by file type:**
Another popular way to structure projects is to group similar files together.
```
api/
├─ APIUtils.js
├─ APIUtils.test.js
├─ ProfileAPI.js
└─ UserAPI.js
components/
├─ Avatar.js
├─ Avatar.css
├─ Feed.js
├─ Feed.css
├─ FeedStory.js
├─ FeedStory.test.js
├─ Profile.js
├─ ProfileHeader.js
└─ ProfileHeader.css
```
124. What are the popular packages for animation?
*React Transition Group* and *React Motion* are popular animation packages in React ecosystem.
125. What is the benefit of styles modules?
It is recommended to avoid hard coding style values in components. Any values that are likely to be used across different UI components should be extracted into their own modules.
For example, these styles could be extracted into a separate component:
```javascript
export const colors = {
white,
black,
blue
}
export const space = [
0,
8,
16,
32,
64
]
```
And then imported individually in other components:
```javascript
import { space, colors } from './styles'
```
126. What are the popular React-specific linters?
ESLint is a popular JavaScript linter. There are plugins available that analyse specific code styles. One of the most common for React is an npm package called `eslint-plugin-react`. By default, it will check a number of best practices, with rules checking things from keys in iterators to a complete set of prop types. Another popular plugin is `eslint-plugin-jsx-a11y`, which will help fix common issues with accessibility. As JSX offers slightly different syntax to regular HTML, issues with `alt` text and `tabindex`, for example, will not be picked up by regular plugins.
127. How to make AJAX call and in which component lifecycle methods should I make an AJAX call?
You can use AJAX libraries such as Axios, jQuery AJAX, and the browser built-in `fetch`. You should fetch data in the `componentDidMount()` lifecycle method. This is so you can use `setState()` to update your component when the data is retrieved.
For example, the employees list fetched from API and set local state:
```jsx harmony
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
employees: [],
error: null
}
}
componentDidMount() {
fetch('https://api.example.com/items')
.then(res => res.json())
.then(
(result) => {
this.setState({
employees: result.employees
})
},
(error) => {
this.setState({ error })
}
)
}
render() {
const { error, employees } = this.state
if (error) {
return <div>Error: {error.message}</div>;
} else {
return (
<ul>
{employees.map(item => (
<li key={employee.name}>
{employee.name}-{employees.experience}
</li>
))}
</ul>
)
}
}
}
```
128. What are render props?
**Render Props** is a simple technique for sharing code between components using a prop whose value is a function. The below component uses render prop which returns a React element.
```jsx harmony
<DataProvider render={data => (
<h1>{`Hello ${data.target}`}</h1>
)}/>
```
Libraries such as React Router and DownShift are using this pattern.
Comments
Post a Comment
please do not enter any spam link in the comment box