- author: CodeDonor
Refactoring React Components for Smooth Functionality
In our project development, we have now completed the refactor on the redox side of things. Therefore, it is time to shift our focus back to refactor the React side. In this article, we will be discussing the necessary steps to refactor React components in a way that will result in a smooth and functional application.
Refactoring Components in React
To begin, let's go into our components directory and find the add cell TSX file. Here are the necessary changes to make:
Change "insert cell before" action creator to "insert cell after". This change is essential because it will result in the newly added cells appearing below the current cell instead of making them appear above it.
Update your "to button on click" functions to reflect the change made above. So now, "insert cell after" should be the function that appears.
Updating Cell List Component
The second and final refactor will be inside of the cell list. Here is what you need to do:
When rendering out the list of cells, ensure that you always show the cell itself through cellist item and then the add cell component. To do this, swap the two things around so that the cell list item shows before the add cell.
Rather than displaying the add cell component below the rendered cells, we will put it above like so.
The add cell component receives a prop of "next cell ID". The name of this prop should be changed to "previous cell ID" to make it more consistent.
The "new cell ID" in the add cell component must be changed to "previous cell ID" here as well.
Update the prop name inside of our argument list.
Make sure you pass through previous cell ID on both of the on-click functions.
Testing the Refactor
Now that we have completed the refactor, it's time to test the final version. Follow these steps to confirm that all is well:
Refresh the application and ensure that any previous errors are resolved.
Add a new cell, and it should appear below the current cell.
Delete some of the code cells to get a better look at what you are doing.
Add a new text cell at the very top.
Add a new text cell at the very end.
Add a new code cell.
If all of the above functions work, then congratulations; you have successfully refactored your React components.
In conclusion, refactoring is an essential process in any project development cycle. Though it might seem challenging, it always pays off in the long run. Through the steps outlined above, you will be able to have a smooth and functional application ready to go live.