React JS and state management issues

Christopher Overton
3 min readSep 13, 2020

--

A recent front-end design problem goes as follows regarding a blog site:

  1. Having a generic template in creating text and image layouts, how to create dynamic states for text and image (e.g., animation) attributes with a scroll position in the visible view window?
  2. An added problem with React JS and state variable is that while one could initialize an empty state array, adding dynamically variables to this state array, creates a referencing problem with the variable state changes in the array, instead for the template, I’ve found the workaround requiring a static set of state variables for a one size fits all approach to the blog post component.

Why this method as opposed to procedural addition in an array? The problem when instancing say the variable in state array in render() component is that the state array variable is a pass by value from the state array as opposed to a reference. This becomes a problem when the state array variable changes and a re render of the component is necessary. As in this instance, I wished simply to update based upon a scroll listener function the className from an animation opacity fade in of text and image elements.

A call to the setter functions of the state elements are shown above.

The references assigned when rendering html components is important for both image and text since it is used to recall the top position of each element from bounding rectangle. This position is relative the window.innerHeight. Noting this top position changes as the scroll position changes.

3. Why add so many references and state variables if they are potentially unused? In this case, I wanted a generalized template for loading blog text content. This blog text content would have embedded a simplified custom markup of my own creation basically for simple layout formatting. In generalizing the procedure for markup and parsing this markup, I could avoid having unique layout procedures and create a variation of layouts without having to write blog post specific component instances in every case. One blog post might have a gallery of both landscape and portrait images together or separately relative to text below, while another would have single images (likely landscape). The custom blog post content parser would read as necessary text content and then layout images relative to corresponding text, and this is done procedural.

Here is the parse and initializing procedure for the given blogpost

Once the pdat data object containing images and text have been initialized for the blogpost, rendering is now done as follows:

--

--

Recommended from Medium

Lists