FrontendDeveloper.in

React Interview Questions

Filter by topic:
  • 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:

  • 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,
    };
    
  • 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:

  • 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().

  • 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.

  • 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'} />
    
  • 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>
    
  • 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>
    );
    }
    }
    
  • 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"));
    
  • 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.

  • 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"));
    
  • 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);
    });
    
  • 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
    }}
    />
    
  • 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.