EzDevInfo.com

reactjs interview questions

Top reactjs frequently asked interview questions

loop inside React JSX

I'm trying to do something like the following in React jsx (where ObjectRow is a separate component)

<tbody>
    for (var i=0; i < numrows; i++) {
        <ObjectRow/>
    } 
</tbody>

I realize and understand why this isn't valid JSX since JSX maps to function calls, but, coming from template land and being new to JSX, am unsure how I would achieve the above (adding a component multiple times).


Source: (StackOverflow)

How to have conditional elements and keep DRY with Facebook React's JSX?

How do I optionally include an element in JSX? Here is an example using a banner that should be in the component if it has been passed in. What I want to avoid is having to duplicate HTML tags in the if statement.

render: function () {
    var banner;
    if (this.state.banner) {
        banner = <div id="banner">{this.state.banner}</div>;
    } else {
        banner = ?????
    }
    return (
        <div id="page">
            {banner}
            <div id="other-content">
                blah blah blah...
            </div>
        </div>
    );
}

Source: (StackOverflow)

Advertisements

Where should ajax request be made in Flux app?

I'm creating a react.js application with flux architecture and I am trying figure out where and when a request for data from the server should be made. Is there a any example for this. (Not TODO app!)


Source: (StackOverflow)

Why is React's concept of Virtual DOM said to be more performant than dirty model checking?

I saw a React dev talks at http://www.youtube.com/watch?v=x7cQ3mrcKaY and speaker mentioned that dirty-check of the model can be slow. But isn't calculating the diff between virtual DOMs actually even less performant since virtual DOM in most of the cases should be bigger than model, is it?

I really like the potential power of Virtual DOM (especially server-side rendering) but I would like to know all pros and cons.


Source: (StackOverflow)

Why use Redux over Facebook Flux?

I've read this answer, reducing boilerplaite, looked at few GitHub examples and even tried redux a little bit (todo apps).

As I understand, official redux doc motivations provide pros comparing to traditional MVC architectures. BUT it doesn't provide an answer to the question:

Why you should use Redux over Facebook Flux?

Is that only a question of programming styles: functional vs non-functional? Or the question is in abilities/dev-tools that follow from redux approach? Maybe scaling? Or testing?

Am I right if I say that redux is a flux for people who comes from functional languages?

To answer this question you may compare complexity of implementation redux's motivation points on flux vs redux.

Here are motivation points from official redux doc motivations:

  1. Handling optimistic updates (as I understand, it hardly depends on 5th point. Is it hard to implement it in fb flux?)
  2. Rendering on the server (fb flux also can do this. Any benefits comparing to redux?)
  3. Fetching data before performing route transitions (Why it can't be achieved in fb flux? What's the benefits?)
  4. Hot reload (It's possible with React Hot Reload. Why do we need redux?)
  5. Undo/Redo functionality
  6. Any other points? Like persisting state...

Source: (StackOverflow)

In Flux architecture, how do you manage Store lifecycle?

I'm reading about Flux but the example Todo app is too simplistic for me to understand some key points.

Imagine a single-page app like Facebook that has user profile pages. On each user profile page, we want to show some user info and their last posts, with infinite scroll. We can navigate from one user profile to another one.

In Flux architecture, how would this correspond to Stores and Dispatchers?

Would we use one PostStore per user, or would we have some kind of a global store? What about dispatchers, would we create a new Dispatcher for each “user page”, or would we use a singleton? Finally, what part of the architecture is responsible for managing the lifecycle of “page-specific” Stores in response to route change?

Moreover, a single pseudo-page may have several lists of data of the same type. For example, on a profile page, I want to show both Followers and Follows. How can a singleton UserStore work in this case? Would UserPageStore manage followedBy: UserStore and follows: UserStore?


Source: (StackOverflow)

Should flux stores, or actions (or both) touch external services?

Should the stores maintain their own state and have the ability to call network and data storage services in doing so ...in which case the actions are just dumb message passers,

-OR-

...should the stores be dumb recipients of immutable data from the actions (and the actions be the ones that fetch/send data between external sources? Store in this instance would act as view-models and would be able to aggregate / filter their data prior to setting their own state base on the immutable data they were fed by the action.

It seems to me that it should be one or the other (rather than a mix of both). If so, why is one preferred / recommended over the other?


Source: (StackOverflow)

Using mixins vs components for code reuse in Facebook React

I'm beginning to use Facebook React in a Backbone project and so far it's going really well.
However, I noticed some duplication creeping into my React code.

For example, I have several form-like widgets with states like INITIAL, SENDING and SENT. When a button is pressed, the form needs to be validated, a request is made, and then state is updated. State is kept inside React this.state of course, along with field values.

If these were Backbone views, I would have extracted a base class called FormView but my impression was that React neither endorses nor supports subclassing to share view logic (correct me if I'm wrong).

I've seen two approaches to code reuse in React:

Am I correct that mixins and containers are preferred to inheritance in React? Is this a deliberate design decision? Would it make more sense to use a mixin or a container component for my “form widget” example from second paragraph?

Here's a gist with FeedbackWidget and JoinWidget in their current state. They have a similar structure, similar beginSend method and will both need to have some validation support (not there yet).


Source: (StackOverflow)

React.js inline style best practices

I'm aware that you can specify styles within React classes, like this:

var MyDiv = React.createClass({
  render: function() {
    var style = {
      color: 'white',
      fontSize: 200
    };

    return <div style={style}> Have a good and productive day! </div>;
  }
});

Should I be aiming to do all styling this way, and have no styles at all specified in my CSS file?

Or should I avoid inline styles completely?

It seems odd and messy to do a little bit of both - two places would need to be checked when tweaking styling.


Source: (StackOverflow)

Strategies for server-side rendering of asynchronously initialized React.js components

One of the biggest advantages of React.js is supposed to be server-side rendering. The problem is that the key function React.renderComponentToString() is synchronous which makes it impossible to load any asynchronous data as the component hierarchy is rendered on the server.

Let's say I have a universal component for commenting which I can drop pretty much anywhere on the page. It has only one property, some kind of identificator (for example id of an article bellow which the comments are placed), and everything else is handled by the component itself (loading, adding, managing comments).

I really like the Flux architecture because it makes a lot of things much easier and also it's Stores are perfect for sharing state between server and client. Once my store containing comments is initialized, I can just serialize it and send it from server to client where it is easily restored.

The question is what is the best way to populate my store. During past days I've been googling a lot and I've come across few strategies, none of which seemed really good considering how much this feature of React is being "promoted".

  1. In my opinion, the simplest way is to populate all my stores before the actual rendering begins. That means somewhere outside of the component hierarchy (hooked to my router for example). The problem with this approach is that I would have to pretty much define the page structure twice. Consider a more complex page, for example a blog page with many different components (actual blog post, comments, related posts, newest posts, twitter stream...). I would have to design the page structure using React components and then somewhere else I would have to define the process of populating each required store for this current page. That doesn't seem like a nice solution to me. Unfortunately most isomorphic tutorials are designed this way (for example this great flux-tutorial).

  2. React-async. This approach is perfect. It lets me simply define in a special function in each component how to initialize the state (doesn't matter whether synchronously or asynchronously) and these functions are called as the hierarchy is being rendered to HTML. It works in a way that a component is not rendered until the state is completely initialized. The problem is that it requires Fibers which is, as far as I understand, a Node.js extension that alters the standard JavaScript behavior. Although I really like the result, it still seems to me that instead of finding a solution we changed the rules of the game. And I think we shouldn't be forced to do that to use this core feature of React.js. I'm also not sure about the general support of this solution. Is it possible to use Fiber on standard Node.js webhostings?

  3. I was thinking a little on my own. I haven't really thought trough the implementation details but the general idea is that I would extend the components in similar way to React-async and then I would repeatedly call React.renderComponentToString() on the root component. During each pass I would collect the extending callbacks and then call them at the and of the pass to populate the stores. I would repeat this step until all stores required by current component hierarchy would be populated. There are many things to be solved and I'm especially not sure about the performance.

Did I miss something? Is there another approach/solution? Right now I'm thinking about going the react-async/fibers way but I'm not completely sure about it as explained in the second point.

Update: Related discussion on GitHub. Apparently, there is no official approach or even solution. Maybe the real question is how the React components are intended to be used. Like simple view layer (pretty much my suggestion number one) or like real independent and standalone components?


Source: (StackOverflow)

Can I build Android apps with react native?

The recently launched react native features just iOS app example and docs.


Source: (StackOverflow)

ReactJS Two components communicating

I just got started with ReactJS and am a little stuck on a problem that I have.

My application is essentially a list with filters and a button to change the layout. At the moment I'm using three components: <list />, < Filters /> and <TopBar />, now obviously when I change settings in < Filters /> I want to trigger some method in <list /> to update my view.

How can I make those 3 components interact with each other, or do I need some sort of global data model where I can just make changes to?


Source: (StackOverflow)

Pass props to parent component in React.js

Is there not a simple way to pass a child's props to its parent using events, in React.js?

var Child = React.createClass({
  render: function() {
    <a onClick={this.props.onClick}>Click me</a>
  }
});

var Parent = React.createClass({
  onClick: function(event) {
    // event.component.props ?why is this not available?
  },
  render: function() {
    <Child onClick={this.onClick} />
  }
});

I know you can use controlled components to pass an input's value but it'd be nice to pass the whole kit n' kaboodle. Sometimes the child component contains a set of information you'd rather not have to look up.

Perhaps there's a way to bind the component to the event?

UPDATE – 9/1/2015

After using React for over a year, and spurred on by Sebastien Lorber's answer, I've concluded passing child components as arguments to functions in parents is not in fact the React way, nor was it ever a good idea. I've switched the answer.


Source: (StackOverflow)

Invariant Violation: _registerComponent(...): Target container is not a DOM element

I get this error after a making trivial React example page:

Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element.

Here's my code:

/** @jsx React.DOM */
'use strict';

var React = require('react');

var App = React.createClass({
  render() {
    return <h1>Yo</h1>;
  }
});

React.renderComponent(<App />, document.body);

HTML:

<html>
<head>
  <script src="/bundle.js"></script>
</head>
<body>
</body>
</html>

What does this mean?


Source: (StackOverflow)

ReactJS: Modeling Bi-Directional Infinite Scrolling

Our application uses infinite scrolling to navigate large lists of heterogenous items. There are a few wrinkles:

  • It's common for our users to have a list of 10,000 items and need to scroll through 3k+.
  • These are rich items, so we can only have a few hundred in the DOM before browser performance becomes unacceptable.
  • The items are of varying heights.
  • The items may contain images and we allow the user to jump to a specific date. This is tricky because the user can jump to a point in the list where we need to load images above the viewport, which would push the content down when they load. Failing to handle that means that the user may jump to a date, but then be shifted to an earlier date.

Known, incomplete solutions:

I'm not looking for the code for a complete solution (although that would be great.) Instead, I'm looking for the "React way" to model this situation. Is scroll position state or not? What state should I be tracking to retain my position in the list? What state do I need to keep so that I trigger a new render when I scroll near the bottom or top of what is rendered?


Source: (StackOverflow)