Question

I read this article where it describes making a flash message in a react app:

https://medium.com/@veelenga/displaying-rails-flash-messages-with-react-5f82982f241c

They mention adding a reference in the window object to the FlashMessages object. In this way you can access the FlashMessages object from anywhere in the app and add a new flash message.

// within the FlashMessages constructor
window.flash_messages = this

//In some other object
window.flash_messages.addMessage('Some message')

On one hand, this seems like the type of thing you would want to add globally, but on the other this seems to break the pattern which React tends to espouse which is to keep things isolated in a component. Is this breaking a best practice?

Was it helpful?

Solution

Exposing this of a React component is not a best practice. While it works, there are more desirable ways to accomplish the same tasks. When holding on to an instance of this, the reference could go stale if the component is remounted. Also, since it's not a best practice, as React evolves, it might become more troublesome.

A React application tries to encapsulate all of its state, so that what is rendered is predictable. A big part of what makes React great is that the data flow is generally easy to follow: events trigger setState, data flows down, a new tree is rendered.

From what I understand in this situation, there are two possible paths for the flash_messages:

  1. The server renders flash_messages before the HTTP response has been sent, or
  2. A Rails-JS bridge is sending flash_messages via XHR to the app without refreshing.

In the first case, when our React app is mounted, it can consume these flash messages at construction time, and propagate the sate accordingly. There's no need for external code to interface with React--React can just read flash_messages and do what it needs to.

In the second case, the best approach is that the Rails-JS exposes a listener interface. Then, at React construction time, you can subscribe to events, calling setState accordingly.

In summary: It's better for React to subscribe to events and update its state when necessary instead external code referencing an object's this.

OTHER TIPS

I am by no means an expert in JS or React.js I wold have to agree that making variables globally available is very risky. Is this a solo project. Then to a certain extent the risk is limited.

Without knowing your project is there away you can create a function/method/module that creates the flash message and limit the variables in that to local. Making the module itself globally available through creating an object.

Let me know how it works out.

Licensed under: CC-BY-SA with attribution
scroll top