The current stable version of React is version 17.5
Posted Date:- 2021-09-23 09:18:21
Yes, you can use attach JSX element with other JSX components which is very much similar to nesting HTML elements.
Posted Date:- 2021-09-23 09:17:38
This props.children allow you to pass a component as data to other components.
Posted Date:- 2021-09-23 09:17:01
The best way to redirect a page in React.js depends on what is your use case. Let us get a bit in detail:
If you want to protect your route from unauthorized access, use the component and try this:
Example:
import React from 'react'
import { Redirect } from 'react-router-dom'
const ProtectedComponent = () => {
if (authFails)
return <Redirect to='/login' />
}
return <div> My Protected Component </div>
}
Posted Date:- 2021-09-23 09:15:29
Reloading/Refreshing a page using Javascript:
Use Vanilla JS to call the reload method for the specific page using the following code:
window.location.reload(false);
Posted Date:- 2021-09-23 09:14:27
There are two ways to link one page to another to React:
Using React Router: Use the feature from the react-router to link the first page to the second one.
<Link to ='/href' ></Link>
Posted Date:- 2021-09-23 09:13:39
We have to follow the following two rules to use hooks in React:
* You should call hooks only at the top level of your React functions and not inside the loops, conditions, or nested functions. This is used to ensure that hooks are called in the same order each time a component renders, and it also preserves the state of hooks between multiple useState and useEffect calls.
* You should call hooks from React functions only. Don't call hooks from regular JavaScript functions.
Posted Date:- 2021-09-23 09:11:15
The 'switch' keyword is used to display only a single Route to rendered amongst the several defined Routes. The <Switch> component is used to render components only when the path will be matched. Otherwise, it returns to the not found component.
Posted Date:- 2021-09-23 09:10:09
React Router plays an important role to display multiple views in a single page application. It is used to define multiple routes in the app. When a user types a specific URL into the browser, and if this URL path matches any 'route' inside the router file, the user will be redirected to that particular Route. So, we need to add a Router library to the React app, which allows creating multiple routes with each leading to us a unique view.
<switch>
<h1>React Router Example</h1>
<Route path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</switch>
Posted Date:- 2021-09-23 09:09:22
Ref forwarding is a feature which is used for passing a ref through a component to one of its child components. It can be performed by making use of the React.forwardRef() method. It is particularly useful with higher-order components and specially used in reusable component libraries.
Example-
import React, { Component } from 'react';
import { render } from 'react-dom';
const TextInput = React.forwardRef((props, ref) => (
<input type="text" placeholder="Hello World" ref={ref} />
));
const inputRef = React.createRef();
class CustomTextInput extends React.Component {
handleSubmit = e => {
e.preventDefault();
console.log(inputRef.current.value);
};
render() {
return (
<div>
<form onSubmit={e => this.handleSubmit(e)}>
<TextInput ref={inputRef} />
<button>Submit</button>
</form>
</div>
);
}
}
export default App;
Posted Date:- 2021-09-23 09:08:18
Web browsers can't read JSX directly. This is because the web browsers are built to read the regular JS objects only, and JSX is not a regular JavaScript object.
If you want a web browser to read a JSX file, you must transform the files into a regular JavaScript object. For this purpose, Babel is used.
Posted Date:- 2021-09-23 09:04:01
If a component needs state or lifecycle methods, we should use the class component; otherwise, use the function component. However, after React 16.8, with the addition of Hooks, you could use state, lifecycle methods, and other features that were only available in the class component right in your function component.
Posted Date:- 2021-09-23 09:03:11
There are two possible ways to create a component in React:
Function Components: This is the simplest way to create a component in React. These are the pure JavaScript functions that accept props object as the first parameter and return React elements:
function Greeting({ message }) {
return <h1>{`Hello, ${message}`}</h1>
}
Class Components: The class components method facilitates you to use ES6 class to define a component. The above function component can be written as:
class Greeting extends React.Component {
render() {
return <h1>{`Hello, ${this.props.message}`}</h1>
}
}
Posted Date:- 2021-09-23 09:02:14
Props validation is a tool which helps the developers to avoid future bugs and problems. It makes your code more readable. React components used special property PropTypes that help you to catch bugs by validating data types of values passed through props, although it is not necessary to define components with propTypes.
We can apply validation on props using App.propTypes in React component. When some of the props are passed with an invalid type, you will get the warnings on JavaScript console. After specifying the validation patterns, you need to set the App.defaultProps.
class App extends React.Component {
render() {}
}
Component.propTypes = { /*Definition */};
Posted Date:- 2021-09-23 09:01:06
Although a <div> is used to encapsulate multiple routes inside the Router. The ‘switch’ keyword is used when you want to display only a single route to be rendered amongst the several defined routes. The <switch> tag when in use matches the typed URL with the defined routes in sequential order. When the first match is found, it renders the specified route. Thereby bypassing the remaining routes.
Posted Date:- 2021-09-23 08:58:57
A store is a JavaScript object which can hold the application’s state and provide a few helper methods to access the state, dispatch actions and register listeners. The entire state/ object tree of an application is saved in a single store. As a result of this, Redux is very simple and predictable. We can pass middleware to the store to handle the processing of data as well as to keep a log of various actions that change the state of stores. All the actions return a new state via reducers.
Posted Date:- 2021-09-23 08:57:40
Reducers are pure functions which specify how the application’s state changes in response to an ACTION. Reducers work by taking in the previous state and action, and then it returns a new state. It determines what sort of update needs to be done based on the type of the action, and then returns new values. It returns the previous state as it is, if no work needs to be done.
Posted Date:- 2021-09-23 08:57:03
Actions in React must have a type property that indicates the type of ACTION being performed. They must be defined as a String constant and you can add more properties to it as well. In Redux, actions are created using the functions called Action Creators. Below is an example of Action and Action Creator:
function addTodo(text) {
return {
type: ADD_TODO,
text
}
}
Posted Date:- 2021-09-23 08:56:20
Redux uses ‘Store’ for storing the application’s entire state at one place. So all the component’s state are stored in the Store and they receive updates from the Store itself. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.
Posted Date:- 2021-09-23 08:55:31
* Single source of truth: The state of the entire application is stored in an object/ state tree within a single store. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.
* State is read-only: The only way to change the state is to trigger an action. An action is a plain JS object describing the change. Just like state is the minimal representation of data, the action is the minimal representation of the change to that data.
* Changes are made with pure functions: In order to specify how the state tree is transformed by actions, you need pure functions. Pure functions are those whose return value depends solely on the values of their arguments.
Posted Date:- 2021-09-23 08:55:02
Flux is an architectural pattern which enforces the uni-directional data flow. It controls derived data and enables communication between multiple components using a central Store which has authority for all data. Any update in data throughout the application must occur here only. Flux provides stability to the application and reduces run-time errors.
Posted Date:- 2021-09-23 08:54:10
In React, it is necessary to start component names with a capital letter. If we start the component name with lower case, it will throw an error as an unrecognized tag. It is because, in JSX, lower case tag names are considered as HTML tags.
Posted Date:- 2021-09-23 08:53:05
Keys are used for identifying unique Virtual DOM Elements with their corresponding data driving the UI. They help React to optimize the rendering by recycling all the existing elements in the DOM. These keys must be a unique number or string, using which React just reorders the elements instead of re-rendering them. This leads to increase in application’s performance.
Posted Date:- 2021-09-23 08:52:08
Pure components are the simplest and fastest components which can be written. They can replace any component which only has a render(). These components enhance the simplicity of the code and performance of the application.
Posted Date:- 2021-09-23 08:51:44
HOC can be used for many tasks like:
* Code reuse, logic and bootstrap abstraction
* Render High jacking
* State abstraction and manipulation
* Props manipulation
Posted Date:- 2021-09-23 08:49:15
Yes, after learning ReactJS, it becomes easier to learn React Native. React Native is an open-source mobile application framework that is used to develop applications for Android, iOS, Web, and UWP. Furthermore, with the knowledge of React Native, you can easily switch to mobile app development.
Posted Date:- 2021-09-23 08:47:25
The following are the prerequisites to learn React: Basic knowledge of HTML, CSS, and JavaScript ES5. Basic understanding of JavaScript ES6 features.
Posted Date:- 2021-09-23 08:47:04
React JS is known to have an easier learning curve as compared to other libraries, like Angular and Node JS. Those who already know JavaScript, won’t have to spend much time learning React JS. It usually takes around 4 to 5 days to learn React Js basics, depending on your learning capabilities.
Posted Date:- 2021-09-23 08:46:23
React JS is used to develop high-performing, dynamic, and responsive UI for web interfaces. It is also used for handling the view layer for web applications.
Posted Date:- 2021-09-23 08:46:03
To become a successful React JS developer, you must develop technical skills, such as knowledge of JavaScript, HTML, CSS; basic understanding of JavaScript ES6 features, and beyond; and understanding of React.js and its core principles. In addition to these technical skills, you need to have good people skills and interpersonal skills.
Posted Date:- 2021-09-23 08:45:34
Styled Components is an open-source CSS-in-JS library that bridges the gap between components and styling. It is the successor of CSS Modules. Styled components are a way to write CSS that’s scoped to a single component and cannot leak to any other element in the page. It allows users to write plain CSS in their components without worrying about class name collisions.
The Styled Components provides:
1. Automatic critical CSS
2. Easier deletion of CSS
3. No class name bugs
4. Dynamic and intuitive styling
Posted Date:- 2021-09-23 08:45:10
There are four ways to style React Component:
1. Inline Styling
2. CSS Module
3. Styled Components
4. CSS Stylesheet
Posted Date:- 2021-09-23 08:44:29
CSS Module is a CSS file but with a key difference. Every class name and animation inside a CSS module is by default scoped locally to the component that is importing it. It is available only for the component which imports it and cannot be applied to any other components without your permission. It means that one can use virtually any valid name for the classes, without worrying about conflicts with other class names in the application. You can create a CSS Module file with the .module.css extension.
Posted Date:- 2021-09-23 08:43:52
Component Driven Development (CDD) is a methodology that holds the developing process which is revolving around the components. It is a process that creates UIs from the bottom up by starting at the components level and ending at the pages or screen level. It is a concept that applies to pattern libraries, design systems, and modern JavaScript frameworks.
Posted Date:- 2021-09-23 08:43:27
The ScrollView component is a generic scrolling container. It can contain multiple components and views. However, the scrollable items need not be homogeneous. It enables you to scroll both vertically and horizontally by setting the horizontal property.
Posted Date:- 2021-09-23 08:43:08
Flexbox is a layout implementation in React Native. It offers an efficient way to create UIs and control positioning in React Native. It provides 3 properties, namely flexDirection, justifyContent, and alignItems to achieve the desired layout.
Posted Date:- 2021-09-23 08:42:50
We can modularize code by using the export and import properties. They help in writing the components separately in different files.
//ChildComponent.jsx
export default class ChildComponent extends React.Component {
render() {
return(
<div>
<h1>This is a child component</h1>
</div>
);
}
}
//ParentComponent.jsx
import ChildComponent from './childcomponent.js';
class ParentComponent extends React.Component {
render() {
return(
<div>
<App />
</div>
);
}
}
Posted Date:- 2021-09-23 08:39:40
Following are the cases when refs should be used:
1. When you need to manage focus, select text or media playback
2. To trigger imperative animations
3. Integrate with third-party DOM libraries
Posted Date:- 2021-09-23 08:39:00
Actions are plain JavaScript objects that have a type field. Actions must have a type property that indicates the type of Action being performed. They must be defined as a String constant and allow you to add more properties to it. We can create actions using the functions called Action Creators.
Example:
function addTodo(text) {
return {
type: ADD_TODO,
text
}
}
Posted Date:- 2021-09-23 08:38:27
Reducers are pure functions that describe how the state of the application changes when an action is triggered. Reducers take the previous state and action and then return a new state.
In simple terms, if you repeat the same test with the same input as arguments, you can always expect the same output.
Posted Date:- 2021-09-23 08:38:01
Refs is the short hand for References in React. It is an attribute which helps to store a reference to a particular React element or component, which will be returned by the components render configuration function. It is used to return references to a particular element or component returned by render(). They come in handy when we need DOM measurements or to add methods to the components.
class ReferenceDemo extends React.Component{
display() {
const name = this.inputDemo.value;
document.getElementById('disp').innerHTML = name;
}
render() {
return(
<div>
Name: <input type="text" ref={input => this.inputDemo = input} />
<button name="Click" onClick={this.display}>Click</button>
<h2>Hello <span id="disp"></span> !!!</h2>
</div>
);
}
}
Posted Date:- 2021-09-23 08:37:20
Synthetic events are the objects which act as a cross-browser wrapper around the browser’s native event. They combine the behavior of different browsers into one API. This is done to make sure that the events show consistent properties across different browsers.
Posted Date:- 2021-09-23 08:36:50
Some of the most important lifecycle methods are:
1. componentWillMount() – Executed just before rendering takes place both on the client as well as server-side.
2. componentDidMount() – Executed on the client side only after the first render.
3. componentWillReceiveProps() – Invoked as soon as the props are received from the parent class and before another render is called.
4. shouldComponentUpdate() – Returns true or false value based on certain conditions. If you want your component to update, return true else return false. By default, it returns false.
5. componentWillUpdate() – Called just before rendering takes place in the DOM.
6. componentDidUpdate() – Called immediately after rendering takes place.
7. componentWillUnmount() – Called after the component is unmounted from the DOM. It is used to clear up the memory spaces.
Posted Date:- 2021-09-23 08:36:31
There are three different phases of React component’s lifecycle:
* Initial Rendering Phase: This is the phase when the component is about to start its life journey and make its way to the DOM.
* Updating Phase: Once the component gets added to the DOM, it can potentially update and re-render only when a prop or state change occurs. That happens only in this phase.
* Unmounting Phase: This is the final phase of a component’s life cycle in which the component is destroyed and removed from the DOM.
In case you are facing any challenges with these React interview questions, please comment on your problems in the section below.
Posted Date:- 2021-09-23 08:35:33
The three fundamental principles of Redux are:
1. Single source of truth. It means that the state of your application is stored in an object tree within a single store. The single state tree will make it easier to make changes and inspect the application.
2. State is read-only. It means that the only way to change the state is to trigger an action.
3. Changes are made with pure functions. You need pure functions to specify how the state tree is transformed by actions.
Posted Date:- 2021-09-23 08:23:13
Arrow functions are more of brief syntax for writing the function expression. They are also called ‘fat arrow‘ (=>) the functions. These functions allow to bind the context of the components properly since in ES6 auto binding is not available by default. Arrow functions are mostly useful while working with the higher order functions.
//General way
render() {
return(
<MyInput onChange={this.handleChange.bind(this) } />
);
}
//With Arrow Function
render() {
return(
<MyInput onChange={ (e) => this.handleOnChange(e) } />
);
}
Posted Date:- 2021-09-23 08:22:17
Components are the building blocks of a React application’s UI. These components split up the entire UI into small independent and reusable pieces. Then it renders each of these components independent of each other without affecting the rest of the UI.
Posted Date:- 2021-09-23 08:20:34
A callback function which will be invoked when setState has finished and the component is re-rendered.
Since the setState is asynchronous, which is why it takes in a second callback function. With this function, we can do what we want immediately after state has been updated.
Posted Date:- 2021-09-23 08:20:04
React.cloneElement clone and return a new React element using using the passed element as the starting point. The resulting element will have the original element's props with the new props merged in shallowly. New children will replace existing children. key and ref from the original element will be preserved.
React.cloneElement only works if our child is a single React element. For almost everything {this.props.children} is the better solution. Cloning is useful in some more advanced scenarios, where a parent send in an element and the child component needs to change some props on that element or add things like ref for accessing the actual DOM element.
Posted Date:- 2021-09-23 08:19:43
Redux is composed of the following components:
Action — Actions are payloads of information that send data from our application to our store. They are the only source of information for the store. We send them to the store using store.dispatch(). Primarly, they are just an object describes what happened in our app.
Reducer — Reducers specify how the application’s state changes in response to actions sent to the store. Remember that actions only describe what happened, but don’t describe how the application’s state changes. So this place determines how state will change to an action.
Store — The Store is the object that brings Action and Reducer together. The store has the following responsibilities: Holds application state; Allows access to state via getState(); Allows state to be updated via dispatch(action); Registers listeners via subscribe(listener); Handles unregistering of listeners via the function returned by subscribe(listener).
It’s important to note that we’ll only have a single store in a Redux application. When we want to split your data handling logic, we’ll use reducer composition instead of many stores.
Posted Date:- 2021-09-23 08:16:12