FrontendDeveloper.in

React Interview Questions

  • Question 91

    How to implement _default_ or _NotFound_ page?

    A <Switch> renders the first child <Route> that matches. A <Route> with no path always matches. So you just need to simply drop path attribute as below

    <Switch>
    <Route exact path="/" component={Home} />
    <Route path="/user" component={User} />
    <Route component={NotFound} />
    </Switch>
    
  • Question 92

    How to get history on React Router v4?

    Below are the list of steps to get history object on React Router v4,

    1. 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 */
    });
    
    1. You should use the <Router> 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(
    <Router history={history}>
    <App />
    </Router>,
    holder
    );
    
    1. 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");
    
  • Question 93

    How to perform automatic redirect after login?

    The react-router package provides <Redirect> component in React Router. Rendering a <Redirect> will navigate to a new location. Like server-side redirects, the new location will override the current location in the history stack.

    import { Redirect } from "react-router";
    
    export default function Login {
    if (this.state.isLoggedIn === true) {
    return <Redirect to="/your/redirect/page" />;
    } else {
    return <div>{"Login Please"}</div>;
    }
    }
    

    See Class

    import React, { Component } from "react";
    import { Redirect } from "react-router";
    
    export default class LoginComponent extends Component {
    render() {
    if (this.state.isLoggedIn === true) {
    return <Redirect to="/your/redirect/page" />;
    } else {
    return <div>{"Login Please"}</div>;
    }
    }
    }
    

    React Internationalization

  • Question 94

    What is React Intl?

    The React Intl library makes internationalization 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.

  • Question 95

    What are the main features of React Intl?

    Below are the main features of React Intl,

    1. Display numbers with separators.
    2. Display dates and times correctly.
    3. Display dates relative to "now".
    4. Pluralize labels in strings.
    5. Support for 150+ languages.
    6. Runs in the browser and Node.
    7. Built on standards.
  • Question 96

    What are the two ways of formatting in React Intl?

    The library provides two ways to format strings, numbers, and dates:

    1. Using react components:
    <FormattedMessage
    id={"account"}
    defaultMessage={"The amount is less than minimum balance."}
    />
    
    1. Using an API:
    const messages = defineMessages({
    accountMessage: {
    id: "account",
    defaultMessage: "The amount is less than minimum balance.",
    },
    });
    
    formatMessage(messages.accountMessage);
    
  • Question 97

    How to use `<FormattedMessage>` as placeholder using React Intl?

    The <Formatted... /> components from react-intl return elements, not plain text, so they can't be used for placeholders, alt text, etc. In that case, you should use lower level API formatMessage(). You can inject the intl object into your component using injectIntl() higher-order component and then format the message using formatMessage() available on that object.

    import React from "react";
    import { injectIntl, intlShape } from "react-intl";
    
    const MyComponent = ({ intl }) => {
    const placeholder = intl.formatMessage({ id: "messageId" });
    return <input placeholder={placeholder} />;
    };
    
    MyComponent.propTypes = {
    intl: intlShape.isRequired,
    };
    
    export default injectIntl(MyComponent);
    
  • Question 98

    How to access current locale with React Intl?

    You can get the current locale in any component of your application using injectIntl():

    import { injectIntl, intlShape } from "react-intl";
    
    const MyComponent = ({ intl }) => (
    );
    
    MyComponent.propTypes = {
    intl: intlShape.isRequired,
    };
    
    export default injectIntl(MyComponent);
    
  • Question 99

    How to format date using React Intl?

    The injectIntl() higher-order component will give you access to the formatDate() method via the props in your component. The method is used internally by instances of FormattedDate and it returns the string representation of the formatted date.

    import { injectIntl, intlShape } from "react-intl";
    
    const stringDate = this.props.intl.formatDate(date, {
    year: "numeric",
    month: "numeric",
    day: "numeric",
    });
    
    const MyComponent = ({ intl }) => (
    );
    
    MyComponent.propTypes = {
    intl: intlShape.isRequired,
    };
    
    export default injectIntl(MyComponent);
    

    React Testing

  • Question 100

    What is Shallow Renderer in React testing?

    Shallow rendering is useful for writing unit test cases in React. It lets you render a component one level deep and assert facts about what its render method returns, without worrying about the behavior of child components, which are not instantiated or rendered.

    For example, if you have the following component:

    function MyComponent() {
    return (
    <span className={"heading"}>{"Title"}</span>
    <span className={"description"}>{"Description"}</span>
    );
    }
    

    Then you can assert as follows:

    import ShallowRenderer from "react-test-renderer/shallow";
    
    // in your test
    const renderer = new ShallowRenderer();
    renderer.render(<MyComponent />);
    
    const result = renderer.getRenderOutput();
    
    expect(result.type).toBe("div");
    expect(result.props.children).toEqual([
    <span className={"heading"}>{"Title"}</span>,
    <span className={"description"}>{"Description"}</span>,
    ]);
    
  • Question 101

    What is `TestRenderer` package in React?

    This package provides a renderer that can be used to render components to pure JavaScript objects, without depending on the DOM or a native mobile environment. This package makes it easy to grab a snapshot of the platform view hierarchy (similar to a DOM tree) rendered by a ReactDOM or React Native without using a browser or jsdom.

    import TestRenderer from "react-test-renderer";
    
    const Link = ({ page, children }) => <a href={page}>{children}</a>;
    
    const testRenderer = TestRenderer.create(
    <Link page={"https://www.facebook.com/"}>{"Facebook"}</Link>
    );
    
    console.log(testRenderer.toJSON());
    // {
    //   type: 'a',
    //   props: { href: 'https://www.facebook.com/' },
    //   children: [ 'Facebook' ]
    // }
    
  • Question 103

    What is Jest?

    Jest is a JavaScript unit testing framework created by Facebook based on Jasmine and provides automated mock creation and a jsdom environment. It's often used for testing components.

  • Question 104

    What are the advantages of Jest over Jasmine?

    There are couple of advantages compared to Jasmine:

    • Automatically finds tests to execute in your source code.
    • Automatically mocks dependencies when running your tests.
    • Allows you to test asynchronous code synchronously.
    • Runs your tests with a fake DOM implementation (via jsdom) so that your tests can be run on the command line.
    • Runs tests in parallel processes so that they finish sooner.
  • Question 105

    Give a simple example of Jest test case

    Let's write a test for a function that adds two numbers in sum.js file:

    const sum = (a, b) => a + b;
    
    export default sum;
    

    Create a file named sum.test.js which contains actual test:

    import sum from "./sum";
    
    test("adds 1 + 2 to equal 3", () => {
    expect(sum(1, 2)).toBe(3);
    });
    

    And then add the following section to your package.json:

    {
    "scripts": {
    "test": "jest"
    }
    }
    

    Finally, run yarn test or npm test and Jest will print a result:

    $ yarn test
    PASS ./sum.test.js
    ✓ adds 1 + 2 to equal 3 (2ms)
    

    React Redux

Get LinkedIn Premium at Rs 399