Part 1: from scratchRead the introduction
in this part I'll be explaining the first commit, source code for that can be found here:
Creating the project:run this command (this is using nodeJS binary) :
npx create-react-app react-nutracker
this will initialize the directories and we are ready to start adding our code.
this is a command line tool created by react team to make initializing as easy as possible because it can be overwhelming for people to configure everything, let's focus on react for now and not the details that can be done later.
you can also start the application and it will work:
npm install --save bootstrap
import bootstrap in the index.js file.
The First NUtracker Component: Search box
1- I added the following directories: components, containers, repos, model
2- in component/search the initial version of SearchBox component:
and used here in Dashboard Component:
- The dashboard component stores the results in the state
- It passes to the searchBox what to do when the user enters a new search term (onTermChange callback)
- It also passes the results of the search for the search box to render AFTER fetching the results from the food repo (mock for a call to food REST api). the reason to have this kind of design is to keep search box a dumb component that can be reused again without it being aware of how to get the results. it's only a presentation component (i.e. it just renders html and notifies its container of any user events it receives)
- The dashboard is a container component, which means it manages one or many presentation components and provide them with the props they need to function either from server or whatever, and it also manages what to do when an event is raised by the child components, in this example it calls foodRepo to get foods based on what the user has input in the box.
- Note that when we get the results from food repo we store them in the state in a key value generic properties, to allow the search box to render the results without knowing what kind of results it is, it could be foods, articles, cats, whatever.
- Also the key is needed by react when you render a list of anything or you will get an error, a property called key is needed in the html elements for react to work.
- foodRepo and model is something I preferred to do, but you can organize the way you want.
Part two: Adding Redux. : http://dev.basharallabadi.com/2018/09/part-2-nutracker-reactjs-application.html