React 2of4 Flashcards
#101-200 (101 cards)
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’

