In ReactJS tutorial you are guided in the building of a commenting system. It’s a very useful tutorial to understand ReactJS library, but there are some design choices I can’t fully understand.
So let’s start from the initial setup:
The system is composed of three components: CommentBox, CommentList, Comment and CommentForm.
The hierarchy is the following
CommentBox
CommentList
Comment
CommentForm
The tutorial then implements all the data-fetching logic in the CommentBox component, which then pass this data to CommentList that renders it in the DOM.
Q1: Why? Is an arbitrary choice or there is some reasoning behind?
Then, when the tutorial come to the logic of new comments submission, it states:
When a user submits a comment, we will need to refresh the list of comments to include the new one. It makes sense to do all of this logic in CommentBox since CommentBox owns the state that represents the list of comments.
Q2: Why CommentBox represents a list of comments when there is another component representing it (CommentList, as the name seems to suggest)?
Further, implementing the submission logic, the code handling the comment POST to the server is part of the CommentBox component, wrapped in a method which is passed to CommentForm as a callback. So when the CommentForm form is submitted, it calls this CommentBox function to perform the server request, while the rest of the logic is implemented in CommentForm’s functions.
Q3: Why isn’t all submission logic implemented in CommentForm?
EDIT: as I stated in a comment, ” I already understood the application architecture and the concept of box. I’m arguing about the “individual implementation” details and why some choices are preferable than others“
The CommentBox
component owns the business logic. CommentList
, Comment
and CommentForm
are visible representations of data (also known as views). The latter is more of a collection bucket for user inserted data.
When CommentBox
owns all the actual logic it is easy to maintain since you won’t have your logic scattered across multiple areas/objects. Instead it’s packed into one.
3
The way the hierarchy works is this:
Comment Box holds instances of a Comment List which holds and lists Comments and a Comment Form which is used to submit additional comments.
You thus have a container on a web page, a “box” in standard web jargon. This box then has two subcomponents, a List and a Form. The list holds elements that have been submitted and are being displayed while the form deals with items in the process of being entered for display.
How that display and submission works is a matter of individual implementation. You could remove the form and the box would still operate correctly. The box exists so that the list and the form are treated uniformly for display purposes.
1