FrontendDeveloper.in

React Interview Questions

  • Question 61

    How do you access props in attribute quotes?

    React (or JSX) doesn't support variable interpolation inside an attribute value. The below representation won't work:

    But you can put any JS expression inside curly braces as the entire attribute value. So the below expression works:

    Using template strings will also work:

  • Question 62

    What is React proptype array with shape?

    If you want to pass an array of objects to a component with a particular shape then use React.PropTypes.shape() as an argument to React.PropTypes.arrayOf().

    ReactComponent.propTypes = {
    arrayWithShape: React.PropTypes.arrayOf(
    React.PropTypes.shape({
    color: React.PropTypes.string.isRequired,
    fontSize: React.PropTypes.number.isRequired,
    })
    ).isRequired,
    };
    
  • Question 63

    How to conditionally apply class attributes?

    You shouldn't use curly braces inside quotes because it is going to be evaluated as a string.

    Instead you need to move curly braces outside (don't forget to include spaces between class names):

    Template strings will also work:

  • Question 64

    What is the difference between React and ReactDOM?

    The react package contains React.createElement(), React.Component, React.Children, and other helpers related to elements and component classes. You can think of these as the isomorphic or universal helpers that you need to build components. The react-dom package contains ReactDOM.render(), and in react-dom/server we have server-side rendering support with ReactDOMServer.renderToString() and ReactDOMServer.renderToStaticMarkup().

  • Question 65

    Why ReactDOM is separated from React?

    The React team worked on extracting all DOM-related features into a separate library called ReactDOM. React v0.14 is the first release in which the libraries are split. By looking at some of the packages, react-native, react-art, react-canvas, and react-three, it has become clear that the beauty and essence of React has nothing to do with browsers or the DOM.

    To build more environments that React can render to, React team planned to split the main React package into two: react and react-dom. This paves the way to writing components that can be shared between the web version of React and React Native.

  • Question 66

    How to use React label element?

    If you try to render a <label> element bound to a text input using the standard for attribute, then it produces HTML missing that attribute and prints a warning to the console.

    <label for={'user'}>{'User'}</label>
    <input type={'text'} id={'user'} />
    

    Since for is a reserved keyword in JavaScript, use htmlFor instead.

    <label htmlFor={'user'}>{'User'}</label>
    <input type={'text'} id={'user'} />
    
  • Question 67

    How to combine multiple inline style objects?

    You can use spread operator in regular React:

    <button style={{ ...styles.panel.button, ...styles.panel.submitButton }}>
    {"Submit"}
    </button>
    

    If you're using React Native then you can use the array notation:

    <button style={[styles.panel.button, styles.panel.submitButton]}>
    {"Submit"}
    </button>
    
  • Question 68

    How to re-render the view when the browser is resized?

    You can use the useState hook to manage the width and height state variables, and the useEffect hook to add and remove the resize event listener. The [] dependency array passed to useEffect ensures that the effect only runs once (on mount) and not on every re-render.

    import React, { useState, useEffect } from "react";
    function WindowDimensions() {
    const [dimensions, setDimensions] = useState({
    width: window.innerWidth,
    height: window.innerHeight,
    });
    
    useEffect(() => {
    function handleResize() {
    setDimensions({
    width: window.innerWidth,
    height: window.innerHeight,
    });
    }
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
    }, []);
    
    return (
    <span>
    {dimensions.width} x {dimensions.height}
    </span>
    );
    }
    

    <h4>Using Class Component</h4>

    You can listen to the resize event in componentDidMount() and then update the dimensions (width and height). You should remove the listener in componentWillUnmount() method.

    class WindowDimensions extends React.Component {
    constructor(props) {
    super(props);
    this.updateDimensions = this.updateDimensions.bind(this);
    }
    
    componentWillMount() {
    this.updateDimensions();
    }
    
    componentDidMount() {
    window.addEventListener("resize", this.updateDimensions);
    }
    
    componentWillUnmount() {
    window.removeEventListener("resize", this.updateDimensions);
    }
    
    updateDimensions() {
    this.setState({
    width: window.innerWidth,
    height: window.innerHeight,
    });
    }
    
    render() {
    return (
    <span>
    {this.state.width} x {this.state.height}
    </span>
    );
    }
    }
    
  • Question 69

    How to pretty print JSON with React?

    We can use <pre> tag so that the formatting of the JSON.stringify() is retained:

    const data = { name: "John", age: 42 };
    
    function User {
    return <pre>{JSON.stringify(data, null, 2)}</pre>;
    }
    
    const container = createRoot(document.getElementById("container"));
    
    container.render(<User />);
    

    See Class

    const data = { name: "John", age: 42 };
    
    class User extends React.Component {
    render() {
    return <pre>{JSON.stringify(data, null, 2)}</pre>;
    }
    }
    
    React.render(<User />, document.getElementById("container"));
    
  • Question 70

    Why can't you update props in React?

    The React philosophy is that props should be immutable(read only) and top-down. This means that a parent can send any prop values to a child, but the child can't modify received props.

  • Question 71

    How to focus an input element on page load?

    You need to use useEffect hook to set focus on input field during page load time for functional component.

    import React, { useEffect, useRef } from "react";
    
    const App = () => {
    const inputElRef = useRef(null);
    
    useEffect(() => {
    inputElRef.current.focus();
    }, []);
    
    return (
    <input defaultValue={"Won't focus"} />
    <input ref={inputElRef} defaultValue={"Will focus"} />
    );
    };
    
    ReactDOM.render(<App />, document.getElementById("app"));
    

    See Class

    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 (
    <input defaultValue={"Won't focus"} />
    <input
    ref={(input) => (this.nameInput = input)}
    defaultValue={"Will focus"}
    />
    );
    }
    }
    
    ReactDOM.render(<App />, document.getElementById("app"));
    
  • Question 73

    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);
    });
    
  • Question 74

    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.

    style={{
    transform: "rotate(90deg)",
    WebkitTransform: "rotate(90deg)", // note the capital 'W' here
    msTransform: "rotate(90deg)", // 'ms' is the only lowercase vendor prefix
    }}
    />
    
  • Question 75

    How to import and export components using React and ES6?

    You should use default for exporting the components

    import User from "user";
    
    export default function MyProfile {
    return <User type="customer">//...</User>;
    }
    

    See Class

     import React from "react";
     import User from "user";
    
    export default class MyProfile extends React.Component {
    render() {
    return <User type="customer">//...</User>;
    }
    }
    
    

    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.

Get LinkedIn Premium at Rs 399