M
M
Maksimka2016-10-13 21:43:20
React
Maksimka, 2016-10-13 21:43:20

How does React.js server rendering work with browser objects in components?

I heard about server rendering in react, read it, cool, great, I wanted to try it. It seems that all the mechanics are clear - the components can be rendered into a line with ready-made markup and sent to the response.
The essence of the question is this: what if I have a component that, for example, uses some localStorage or something with the DOM in the componentWillMount () method? How then can React correctly render the component in the Node server environment, which does not know about localStorage. Those. we are talking about any objects built into the browser in general.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim, 2016-10-13
@acupofspirt

I may be wrong, but I understand that all browser objects are mocked (as if in tests, that is, for example, "false localStorage" is done, because this is essentially an object that has a getter and setter. For tests, I used - mock-local -storage ). You can "wet" yourself, for this you need to write in global, since in the node environment the global object is not "window". More details can be found in the library code.
Again, let's continue about localStorage, as it is more convenient with a specific example. Why is a mock okay, I think? Because it will be as if a user came to your site who has nothing saved in LS on your site. The main thing is to make it work: localStorage.setItem / getItem, and since you wrote and declared these functions globally, everything will work out (of course, in your code you should have localStorage without window, or you will need to mock not just in global, but in global. window - in other words, we create a window object in the global object).
PS In practice, I did not do serious SS rendering, so I will be glad to hear the opinion of those who have already figured it out. There is information in foreign sources ( for example), and even things with asynchronous requests are well sorted out, but nevertheless, I would like to see more.

_
_ _, 2016-10-13
@AMar4enko

https://facebook.github.io/react/docs/component-sp... The
componentDidMount hook only runs on the client.
Accordingly, if you use the same ref to perform some actions with the DOM, then it makes sense to do this in this hook.
localStorage to use in components seems wrong to me. You store the state (or part of it) in it, and you must have a separate layer to manage the state. In this layer, you can just make the mocks that Maxim described

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question