12 Most Asked ReactJS Questions
KiranPoudel98
Posted on September 18, 2020
ReactJS, also known as React.js or simply React, is a JavaScript library used for building user interfaces and is maintained by Facebook. It is one of the new technology built in 2011 by Jordan Walke, a software engineer at Facebook. So, today we will be talking about the 12 most asked ReactJS questions.
12 Most Asked ReactJS Questions
1. How to programmatically navigate using React Router?
Answer:
React Router v5.1.0 with hooks
There is a new useHistory
hook in React Router >5.1.0. If you are using React >16.8.0 and functional components.
import { useHistory } from "react-router-dom";
function HomeButton() {
const history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
React Router v4
With v4 of React Router, there are three approaches that you can take to programmatic routing within components.
- Use the
withRouter
higher-order component. - Use composition and render a
<Route>
- Use the context.
React Router is mostly a wrapper around the history
library. history
handles interaction with the browser’s window.history
for you with its browser and hash histories. It also provides a memory history which is useful for environments that don’t have a global history. This is particularly useful in mobile app development (react-native
) and unit testing with Node.
A history
instance has two methods for navigating: push
and 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. Typically you will want to use the push
method when you are navigating.
In earlier versions of React Router, you had to create your own history
instance, but in v4 the <BrowserRouter>
, <HashRouter>
, and <MemoryRouter>
components will create a browser, hash, and memory instances for you. React Router makes the properties and methods of the history
instance associated with your router available through the context, under the router
object.
a. Use the withRouter
higher-order component
The withRouter
higher-order component will inject the history
object as a prop of the component. This allows you to access the push
and replace
methods without having to deal with the context
.
import { withRouter } from 'react-router-dom'
// this also works with react-router-native
const Button = withRouter(({ history }) => (
<button
type='button'
onClick={() => { history.push('/new-location') }}
>
Click Me!
</button>
))
b. Use composition and render a <Route>
The <Route>
component isn’t just for matching locations. You can render a pathless route and it will always match the current location. The <Route>
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 = () => (
<Route render={({ history}) => (
<button
type='button'
onClick={() => { history.push('/new-location') }}
>
Click Me!
</button>
)} />
)
c. Use the context
But you probably should not.
The last option is one that you should only use if you feel comfortable working with React’s context model (React’s Context API is stable as of v16).
const Button = (props, context) => (
<button
type='button'
onClick={() => {
// context.history.push === history.push
context.history.push('/new-location')
}}
>
Click Me!
</button>
)
// you need to specify the context type so that it
// is available within the component
Button.contextTypes = {
history: React.PropTypes.shape({
push: React.PropTypes.func.isRequired
})
}
a and b are the simplest choices to implement, so for most use cases, they are your best bets.
2. How to loop inside React JSX?
Answer:
Think of it like you’re just calling JavaScript functions. You can’t use a for
loop where the arguments to a function call would go:
return tbody(
for (var i = 0; i < numrows; i++) {
ObjectRow()
}
)
See how the function tbody
is being passed a for
loop as an argument, and of course that’s a syntax error.
But you can make an array, and then pass that in as an argument:
var rows = [];
for (var i = 0; i < numrows; i++) {
rows.push(ObjectRow());
}
return tbody(rows);
You can use basically the same structure when working with JSX:
var rows = [];
for (var i = 0; i < numrows; i++) {
// note: we add a key prop here to allow react to uniquely identify each
// element in this array. see: https://reactjs.org/docs/lists-and-keys.html
rows.push(<ObjectRow key={i} />);
}
return <tbody>{rows}</tbody>;
Incidentally, the above JavaScript example is almost exactly what that example of JSX transforms into. Play around with Babel REPL to get a feel for how JSX works.
Alternative Answer:
Often map is a good answer.
If this was your code with the for loop:
<tbody>
for (var i=0; i < objects.length; i++) {
<ObjectRow obj={objects[i]} key={i}>
}
</tbody>
You could write it like this with map:
<tbody>
{objects.map(function(object, i){
return <ObjectRow obj={object} key={i} />;
})}
</tbody>
ES6 syntax:
<tbody>
{objects.map((object, i) => <ObjectRow obj={object} key={i} />)}
</tbody>
3. What do these three dots … in React do?
Answer:
That’s property spread notation. It was added in ES2018 (spread for arrays/iterables was earlier, ES2015), but it’s been supported in React projects for a long time via transpilation (as “JSX spread attributes” even though you could do it elsewhere, too, not just attributes).
{...this.props}
spreads out the “own” enumerable properties in props
as discrete properties on the Modal
element you’re creating. For instance, if this.props
contained a: 1
and b: 2
, then
<Modal {...this.props} title='Modal heading' animation={false}>
would be the same as
<Modal a={this.props.a} b={this.props.b} title='Modal heading' animation={false}>
But it’s dynamic, so whatever “own” properties are in props
are included.
Since children
is an “own” property in props
, spread will include it. So if the component where this appears had child elements, they’ll be passed on to Modal
. Putting child elements between the opening tag and closing tags is just syntactic sugar — the good kind — for putting a children
property in the opening tag. Example:
class Example extends React.Component {
render() {
const { className, children } = this.props;
return (
<div className={className}>
{children}
</div>
);
}
}
ReactDOM.render(
[
<Example className="first">
<span>Child in first</span>
</Example>,
<Example className="second" children={<span>Child in second</span>} />
],
document.getElementById("root")
);
.first {
color: green;
}
.second {
color: blue;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
The spread notation is handy not only for that use case, but for creating a new object with most (or all) of the properties of an existing object — which comes up a lot when you’re updating state, since you can’t modify state directly:
this.setState(prevState => {
return {foo: {...prevState.foo, a: "updated"}};
});
That replaces this.state.foo
with a new object with all the same properties as foo
except the a property, which becomes "updated"
:
const obj = {
foo: {
a: 1,
b: 2,
c: 3
}
};
console.log("original", obj.foo);
// Creates a NEW object and assigns it to `obj.foo`
obj.foo = {...obj.foo, a: "updated"};
console.log("updated", obj.foo);
.as-console-wrapper {
max-height: 100% !important;
}
Alternative Answer:
As you know ...
are called Spread Attributes which the name represents it allows an expression to be expanded.
var parts = ['two', 'three'];
var numbers = ['one', ...parts, 'four', 'five']; // ["one", "two", "three", "four", "five"]
And in this case, let’s simplify it.
//just assume we have an object like this:
var person= {
name: 'Alex',
age: 35
}
This:
<Modal {...person} title='Modal heading' animation={false} />
is equal to
<Modal name={person.name} age={person.age} title='Modal heading' animation={false} />
So in short, it’s a neat short-cut, we can say.
4. How to pass props to {this.props.children}?
Answer:
The answer is simple, cloning children with new props.
You can use React.Children to iterate over the children, and then clone each element with new props (shallow merged) using React.cloneElement e.g:
import React, { Children, isValidElement, cloneElement } from 'react';
const Child = ({ doSomething, value }) => (
<div onClick={() => doSomething(value)}>Click Me</div>
);
function Parent({ children }) {
function doSomething(value) {
console.log('doSomething called by child with value:', value);
}
render() {
const childrenWithProps = Children.map(children, child => {
// Checking isValidElement is the safe way and avoids a TS error too.
if (isValidElement(child)) {
return cloneElement(child, { doSomething })
}
return child;
});
return <div>{childrenWithProps}</div>
}
};
ReactDOM.render(
<Parent>
<Child value="1" />
<Child value="2" />
</Parent>,
document.getElementById('container')
);
Fiddle: https://jsfiddle.net/2q294y43/2/
Calling children as a function
You can also pass props to children with render props. In this approach the children (which can be children
or any other prop name) is a function which can accept any arguments you want to pass and returns the children:
const Child = ({ doSomething, value }) => (
<div onClick={() => doSomething(value)}>Click Me</div>
);
function Parent({ children }) {
function doSomething(value) {
console.log('doSomething called by child with value:', value);
}
render() {
// Note that children is called as a function and we can pass args to it
return <div>{children(doSomething)}</div>
}
};
ReactDOM.render(
<Parent>
{doSomething => (
<React.Fragment>
<Child doSomething={doSomething} value="1" />
<Child doSomething={doSomething} value="2" />
</React.Fragment>
)}
</Parent>,
document.getElementById('container')
);
Instead of <React.Fragment>
or simply <>
you can also return an array if you prefer.
Fiddle: https://jsfiddle.net/ferahl/y5pcua68/7/
Alternative Answer:
For a slightly cleaner way to do it, try:
<div>
{React.cloneElement(this.props.children, { loggedIn: this.state.loggedIn })}
</div>
To use with multiple individual children (the child must itself be a component) you can do. Tested in 16.8.6
<div>
{React.cloneElement(props.children[0], { loggedIn: true, testingTwo: true })}
{React.cloneElement(props.children[1], { loggedIn: true, testProp: false })}
</div>
5. What is the difference between React Native and React?
Answer:
ReactJS is a JavaScript library, supporting both front-end web and being run on a server, for building user interfaces and web applications.
React Native is a mobile framework that compiles to native app components, allowing you to build native mobile applications for different platforms (iOS, Android, and Windows Mobile) in JavaScript that allows you to use ReactJS to build your components, and implements ReactJS under the hood.
Both are open-sourced by Facebook.
Alternative Answer:
Here is the React project.
At Facebook, they invented React so JavaScript can manipulate the website DOM faster using the virtual DOM model.
DOM full refresh is slower compared to the React virtual-dom model, which refreshes only parts of the page (read: partial refresh).
As you may understand from this video, Facebook did not invent React because they understood immediately that the partial refresh would be faster than the conventional one. Originally they needed a way to reduce Facebook application re-build time and luckily this brought the partial DOM refresh to life.
React native is just a consequence of React. It is a platform to build native apps using JavaScript.
Prior to React native, you needed to know Java for Android or Objective-C for iPhone and iPad to create native apps.
With React Native it is possible to mimic the behavior of the native app in JavaScript and in the end, you will get platform-specific code as the output. You may even mix the native code with JavaScript if you need to optimize your application further.
As Olivia Bishop said in the video, 85% of the React native code base can be shared among platforms. These would be the components applications typically use and the common logic.
15% of the code is platform-specific. The platform-specific JavaScript is what gives the platform flavor ( and makes the difference in the experience).
The cool thing is this platform-specific code — is already written, so you just need to use it.
6. Understanding unique keys for array children in React.js
Answer:
You should add a key to each child as well as each element inside children.
This way React can handle the minimal DOM change.
Check this example.
Try removing the key={i}
from the <b></b>
element inside the div’s (and check the console).
In the sample, if we don’t give a key to the <b>
element and we want to update only the object.city
, React needs to re-render the whole row vs just the element.
Here is the code:
var data = [{name:'Jhon', age:28, city:'HO'},
{name:'Onhj', age:82, city:'HN'},
{name:'Nohj', age:41, city:'IT'}
];
var Hello = React.createClass({
render: function() {
var _data = this.props.info;
console.log(_data);
return(
<div>
{_data.map(function(object, i){
return <div className={"row"} key={i}>
{[ object.name ,
// remove the key
<b className="fosfo" key={i}> {object.city} </b> ,
object.age
]}
</div>;
})}
</div>
);
}
});
React.render(<Hello info={data} />, document.body);
7. How can you pass a value to the onClick
event in React js?
Answer:
Easy Way
Use an arrow function:
return (
<th value={column} onClick={() => this.handleSort(column)}>{column}</th>
);
This will create a new function that calls handleSort with the right params.
Better Way
Extract it into a sub-component. The problem with using an arrow function in the render call is it will create a new function every time, which ends up causing unneeded re-renders.
If you create a sub-component, you can pass handler and use props as the arguments, which will then re-render only when the props change (because the handler reference now never changes):
Sub-component
class TableHeader extends Component {
handleClick = () => {
this.props.onHeaderClick(this.props.value);
}
render() {
return (
<th onClick={this.handleClick}>
{this.props.column}
</th>
);
}
}
Main component
{this.props.defaultColumns.map((column) => (
<TableHeader
value={column}
onHeaderClick={this.handleSort}
/>
))}
Old Easy Way (ES5)
Use .bind
to pass the parameter you want:
return (
<th value={column} onClick={that.handleSort.bind(that, column)}>{column}</th>
);
Alternative Answer:
There is another way like, currying.
What you can do is create a function that accepts a parameter (your parameter) and returns another function that accepts another parameter (the click event in this case). Then you are free to do with it whatever you want.
ES5:
handleChange(param) { // param is the argument you passed to the function
return function (e) { // e is the event object that returned
};
}
ES6:
handleChange = param => e => {
// param is the argument you passed to the function
// e is the event object that returned
};
And you will use it this way:
<input
type="text"
onChange={this.handleChange(someParam)}
/>
Here is a full example of such usage:
const someArr = ["A", "B", "C", "D"];
class App extends React.Component {
state = {
valueA: "",
valueB: "some initial value",
valueC: "",
valueD: "blah blah"
};
handleChange = param => e => {
const nextValue = e.target.value;
this.setState({ ["value" + param]: nextValue });
};
render() {
return (
<div>
{someArr.map(obj => {
return (
<div>
<label>
{`input ${obj} `}
</label>
<input
type="text"
value={this.state["value" + obj]}
onChange={this.handleChange(obj)}
/>
<br />
<br />
</div>
);
})}
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Note that this approach doesn’t solve the creation of a new instance on each render.
You can also cache/memoize the result of the function.
Here is a naive implementation:
let memo = {};
const someArr = ["A", "B", "C", "D"];
class App extends React.Component {
state = {
valueA: "",
valueB: "some initial value",
valueC: "",
valueD: "blah blah"
};
handleChange = param => {
const handler = e => {
const nextValue = e.target.value;
this.setState({ ["value" + param]: nextValue });
}
if (!memo[param]) {
memo[param] = e => handler(e)
}
return memo[param]
};
render() {
return (
<div>
{someArr.map(obj => {
return (
<div key={obj}>
<label>
{`input ${obj} `}
</label>
<input
type="text"
value={this.state["value" + obj]}
onChange={this.handleChange(obj)}
/>
<br />
<br />
</div>
);
})}
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root" />
8. How to set focus on an input field after rendering?
Answer:
You should do it in componentDidMount
and refs callback
instead. Something like this
componentDidMount(){
this.nameInput.focus();
}
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'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.js"></script>
<div id="app"></div>
Alternative Answer:
For convenience you can use the autoFocus prop to have an input automatically focus when mounted:
<input autoFocus name=...
Note that in JSX it’s autoFocus
(capital F) unlike plain old HTML which is case-insensitive.
9. What is the difference between using constructor vs getInitialState in React / React Native?
Answer:
The two approaches are not interchangeable. You should initialize state in the constructor when using ES6 classes, and define the getInitialState
method when using React.createClass
.
See the official React doc on the subject of ES6 classes.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { /* initial state */ };
}
}
is equivalent to
var MyComponent = React.createClass({
getInitialState() {
return { /* initial state */ };
},
});
Alternative Answer:
The difference between constructor
and getInitialState
is the difference between ES6 and ES5 itself.
getInitialState
is used with React.createClass
and constructor
is used with React.Component
.
Hence the question boils down to the advantages/disadvantages of using ES6 or ES5.
Let’s look at the difference in code
ES5
var TodoApp = React.createClass({
propTypes: {
title: PropTypes.string.isRequired
},
getInitialState () {
return {
items: []
};
}
});
ES6
class TodoApp extends React.Component {
constructor () {
super()
this.state = {
items: []
}
}
};
There is an interesting reddit thread regarding this.
React community is moving closer to ES6. Also, it is considered as the best practice.
There are some differences between React.createClass
and React.Component
. For instance, how
this is handled in these cases. Read more about such differences in this blogpost and facebook’s content on autobinding.
constructor
can also be used to handle such situations. To bind methods to a component instance, it can be prebinded in the constructor
. This is a good material to do such cool stuff.
Some more good material on best practices
Best Practices for Component State in React.js
Converting React project from ES5 to ES6
April 9 2019:
With the new changes in Javascript class API, you don’t need constructor.
You could do
class TodoApp extends React.Component {
this.state = {items: []}
};
This will still get transpiled to constructor format, but you won’t have to worry about it. You can use this format that is more readable.
With React Hooks
From React version 16.8, there’s a new API Called hooks.
Now, you don’t even need a class component to have state. It can even be done in a functional component.
import React, { useState } from 'react';
function TodoApp () {
const items = useState([]);
Note that the initial state is passed as an argument to useState; useState([])
Read more about React Hooks from the official docs.
10. What is the difference between state and props in React?
Answer:
Props and state are related. The state of one component will often become the props of a child component. Props are passed to the child within the render method of the parent as the second argument to React.createElement()
or, if you’re using JSX, the more familiar tag attributes.
<MyChild name={this.state.childsName} />
The parent’s state value of childsName
becomes the child’s this.props.name
. From the child’s perspective, the name prop is immutable. If it needs to be changed, the parent should just change its internal state:
this.setState({ childsName: 'New name' });
and React will propagate it to the child for you. A natural follow-on question is: what if the child needs to change its name prop? This is usually done through child events and parent callbacks. The child might expose an event called, for example, onNameChanged
. The parent would then subscribe to the event by passing a callback handler.
<MyChild name={this.state.childsName} onNameChanged={this.handleName} />
The child would pass its requested new name as an argument to the event callback by calling, e.g., this.props.onNameChanged('New name')
, and the parent would use the name in the event handler to update its state.
handleName: function(newName) {
this.setState({ childsName: newName });
}
Alternative Answer:
For parent-child communication, simply pass props.
Use state to store the data your current page needs in your controller-view.
Use props to pass data & event handlers down to your child components.
These lists should help guide you when working with data in your components.
Props
- are immutable
- which lets React do fast reference checks
- are used to pass data down from your view-controller
- your top-level component
- have better performance
- use this to pass data to child components
State
- should be managed in your view-controller
- your top-level component
- is mutable
- has worse performance
- should not be accessed from child components
- pass it down with props instead
For communication between two components that don’t have a parent-child relationship, you can set up your own global event system. Subscribe to events in componentDidMount(), unsubscribe in componentWillUnmount(), and call setState() when you receive an event. Flux pattern is one of the possible ways to arrange this. – https://facebook.github.io/react/tips/communicate-between-components.html
What Components Should Have State?
Most of your components should simply take some data from props and render it. However, sometimes you need to respond to user input, a server request, or the passage of time. For this you use state.
Try to keep as many of your components as possible stateless. By doing this you’ll isolate the state to its most logical place and minimize redundancy, making it easier to reason about your application.
A common pattern is to create several stateless components that just render data, and have a stateful component above them in the hierarchy that passes its state to its children via props. The stateful component encapsulates all of the interaction logic, while the stateless components take care of rendering data in a declarative way. – https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html#what-components-should-have-state
What Should Go in State?
The state should contain data that a component’s event handlers may change to trigger a UI update. In real apps, this data tends to be very small and JSON-serializable. When building a stateful component, think about the minimal possible representation of its state, and only store those properties in this.state. Inside of render() simply compute any other information you need based on this state. You’ll find that thinking about and writing applications in this way tends to lead to the most correct application, since adding redundant or computed values to state means that you need to explicitly keep them in sync rather than rely on React computing them for you. – https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html#what-should-go-in-state
11. How to use radio buttons in ReactJS?
Answer:
Any changes to the rendering should be change via the state
or props
(react doc).
So here register the event of the input, and then change the state
, which will then trigger the render to show on the footer.
var SearchResult = React.createClass({
getInitialState: function () {
return {
site: '',
address: ''
};
},
onSiteChanged: function (e) {
this.setState({
site: e.currentTarget.value
});
},
onAddressChanged: function (e) {
this.setState({
address: e.currentTarget.value
});
},
render: function(){
var resultRows = this.props.data.map(function(result){
return (
<tbody>
<tr>
<td><input type="radio" name="site_name"
value={result.SITE_NAME}
checked={this.state.site === result.SITE_NAME}
onChange={this.onSiteChanged} />{result.SITE_NAME}</td>
<td><input type="radio" name="address"
value={result.ADDRESS}
checked={this.state.address === result.ADDRESS}
onChange={this.onAddressChanged} />{result.ADDRESS}</td>
</tr>
</tbody>
);
}, this);
return (
<table className="table">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
</tr>
</thead>
{resultRows}
<tfoot>
<tr>
<td>chosen site name {this.state.site} </td>
<td>chosen address {this.state.address} </td>
</tr>
</tfoot>
</table>
);
}
});
Alternative Answer:
Here is the simplest way of implementing radio buttons in ReactJS.
class App extends React.Component {
setGender(event) {
console.log(event.target.value);
}
render() {
return (
<div onChange={this.setGender.bind(this)}>
<input type="radio" value="MALE" name="gender"/> Male
<input type="radio" value="FEMALE" name="gender"/> Female
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
12. How to include bootstrap CSS and JS in the ReactJS app?
Answer:
If you are new to React and using create-react-app
cli setup, run the npm command below to include the latest version of bootstrap.
npm install --save bootstrap
or
npm install --save bootstrap@latest
Then add the following import statement to index.js file
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
or
import 'bootstrap/dist/css/bootstrap.min.css';
don’t forget to use className
as attribute on target elements (react uses className
as an attribute instead of class
).
Alternative Answer:
Via npm, you would run the following:
npm install bootstrap jquery --save
npm install css-loader style-loader --save-dev
If bootstrap 4, also add popper.js
npm install popper.js --save
Add the following (as a new object) to your webpack config loaders:
[ array
{
test: /\.css$/,
loader: 'style-loader!css-loader'
}
Add the following to your index, or layout
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/js/bootstrap.js';
In Conclusion
These are the most commonly asked questions about ReactJS. If you have any suggestions regarding the article, please feel free to comment below. If you need any help, then we would be glad to help you.
We, at Truemark, provide services like web and mobile app development, digital marketing, and website development. So, if you want to work with us, please feel free to contact us.
Hope this article helped you.
This post was first published on DevPostbyTruemark.
Posted on September 18, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024