React 2of4 Flashcards
#101-200
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().
How to listen to state changes?
The componentDidUpdate lifecycle method 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.
componentDidUpdate(object prevProps, object prevState)
Note: The previous releases of ReactJS also uses componentWillUpdate(object nextProps, object nextState) for state changes. It has been deprecated in latest releases.
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.
removeItem(index) {
this.setState({
data: this.state.data.filter((item, i) => i !== index)
})
}
Is it possible to use React without rendering HTML?
It is possible with latest version (>=16.2). Below are the possible options:
render() {
return false
}
render() {
return null
}
render() {
return []
}
render() {
return
}
render() {
return <>>
}
Returning undefined won’t work.
How to pretty print JSON with React?
We can use
tag so that the formatting of the JSON.stringify() is retained: const data = { name: 'John', age: 42 }
class User extends React.Component {
render() {
return (
~~~
{JSON.stringify(data, null, 2)}
)
}
}
React.render(, document.getElementById(‘container’))
~~~
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.
How to focus an input element on page load?
You can do it by creating ref for input element and using it in componentDidMount():
class App extends React.Component{ componentDidMount() { this.nameInput.focus() }
render() {
return (
this.nameInput = input}
defaultValue={‘Will focus’}
/>
)
}
}
ReactDOM.render(, document.getElementById(‘app’))
Also in Functional component (react 16.08 and above)
import React, {useEffect, useRef} from ‘react’;
const App = () =\> { const inputElRef = useRef(null)
useEffect(()=>{
inputElRef.current.focus()
}, [])
return(
)
}
ReactDOM.render(, document.getElementById(‘app’))
What are the possible ways of updating objects in state?
[i] Calling setState() with an object to merge with state:
Using Object.assign() to create a copy of the object:
const user = Object.assign({}, this.state.user, { age: 42 }) this.setState({ user }) Using spread operator:
const user = { ...this.state.user, age: 42 } this.setState({ user })
[ii] Calling setState() with a function:
this.setState(prevState => ({
user: {
…prevState.user,
age: 42
}
}))
(question #109 not given - https://github.com/sudheerj/reactjs-interview-questions#what-is-react )
(question and answer #109 not given)
How can we find the version of React at runtime in the browser?
You can use React.version to get the version.
const REACT_VERSION = React.version
ReactDOM.render(
{React version: ${REACT_VERSION}
}
,
document.getElementById(‘app’)
)
What are the approaches to include polyfills in your create-react-app?
There are approaches to include polyfills in create-react-app,
[i] 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.
import ‘core-js/fn/array/find’
import ‘core-js/fn/array/includes’
import ‘core-js/fn/number/is-nan’
Using Polyfill service:
[ii] Use the polyfill.io CDN to retrieve custom, browser-specific polyfills by adding this line to index.html:
In the above script we had to explicitly request the Array.prototype.includes feature as it is not included in the default feature set.
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:
“scripts”: {
“start”: “set HTTPS=true && react-scripts start”
}
or just run set HTTPS=true && npm start
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.
How to add Google Analytics for React Router?
Add a listener on the history object to record each page view:
history.listen(function (location) {
window.ga(‘set’, ‘page’, location.pathname + location.search)
window.ga(‘send’, ‘pageview’, location.pathname + location.search)
})
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.
componentDidMount() {
this.interval = setInterval(() => this.setState({ time: Date.now() }), 1000)
}
componentWillUnmount() {
clearInterval(this.interval)
}
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.
How to import and export components using React and ES6?
You should use default for exporting the components
import React from ‘react’
import User from ‘user’
export default class MyProfile extends React.Component { render(){ return (
//…
) } } 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.
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.
How to define constants in React?
You can use ES7 static field to define constant.
class MyComponent extends React.Component { static DEFAULT\_PAGINATION = 10 }
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:
[i] Create ref in render method:
this.inputElement = input} />
[ii] Apply click event in your event handler:
this.inputElement.click()
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 plugin. React Native ships with Babel and a set of transforms.
What are the common folder structures for React?
There are two common practices for React project file structure.
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
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
What are the popular packages for animation?
React Transition Group and React Motion are popular animation packages in React ecosystem.
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:
export const colors = {
white,
black,
blue
}
export const space = [
0,
8,
16,
32,
64
]
And then imported individually in other components:
import { space, colors } from ‘./styles’
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.
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:
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
Error: {error.message}
;
} else {
return (
{employees.map(employee => ( * {employee.name}-{employee.experience}
))}
)
}
}
}
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.
(
{Hello ${data.target}
}
)}/>
Libraries such as React Router and DownShift are using this pattern
-
-
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 components of React Router v4?
React Router v4 provides below 3 components:
[i]
[ii]
[iii]
The above components will create browser, hash, and memory history instances. React Router v4 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.
[i] push()
[ii] 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.
[i] 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 }) =\> ( { history.push('/new-location') }} \> {'Click Me!'}
))
[ii] Using component and render props pattern:
The component passes the same props as withRouter(), so you will be able to access the history methods through the history prop.
import { Route } from ‘react-router-dom’
const Button = () => (
(
{ history.push(‘/new-location’) }}
>
{‘Click Me!’}
)} />
)
[iii] Using context:
This option is not recommended and treated as unstable API.
const Button = (props, context) => (
{
context.history.push(‘/new-location’)
}}
>
{‘Click Me!’}
)
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') You should use a polyfill for IE11.
Why you get “Router may have only one child element” warning?
You have to wrap your Route’s in a block because is unique in that it renders a route exclusively.
At first you need to add Switch to your imports:
import { Switch, Router, Route } from ‘react-router’
Then define the routes within block:
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 renders the first child that matches. A with no path always matches. So you just need to simply drop path attribute as below
How to get history on React Router v4?
Below are the list of steps to get history object on React Router v4,
[i] 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 */
})
[ii] You should use the component instead of built-in routers. Import the above history.js inside index.js file:
import { Router } from ‘react-router-dom’
import history from ‘./history’
import App from ‘./App’
ReactDOM.render((
), holder)
[iii] 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 component in React Router. Rendering a will navigate to a new location. Like server-side redirects, the new location will override the current location in the history stack.
import React, { Component } from ‘react’
import { Redirect } from ‘react-router’
export default class LoginComponent extends Component { render() { if (this.state.isLoggedIn === true) { return } else { return
{‘Login Please’}
}
}
}
What is React Intl (Internalization)?
The React Intl (internalization) library makes internalization in React straightforward, with off-the-shelf components and an API that can handle everything from formatting strings, dates, and numbers, to pluralization. React Intl is part of FormatJS which provides bindings to React via its components and API.