Where do I put coding logic in my React Application
I know this answer is late but wanted to add my thoughts. Usually you want to keep presentation components dumb. Meaning your UI components have no logic other then something like a type which may style the component differently. It’s a good idea to pull your logic out into react hooks then using the react hooks in your controlling component. That way all the logic is in your hooks and not in your presentational components making them a lot more independent and reusable.
As you said, React is just the V in the MVC. So, where do you put your business logic?
For small, view-specific business logic, it's ok to put that on the component, as you did. If the business logic is in the component, it's going to be on an event-handler, in the render or any other component method.
If you have non-view-specific business logic, and it runs on the client (or both on the client and server), it's always a good practice to isolate that on a separate JavaScript module. React does not play nice with AMD, so you are better off not using RequireJS for modularization. You should probably use Browserify or Webpack. In this case, all you would have to do is add this to the top or your component file: var myBusinessLogic = require('./myBusinessLogic')
. Now you can delegate processing to this module. This is the prefered way, because JavaScript modules are easily testable using Jest, Jasmine, Karma or Mocha.
There's also a third scenario in which you delegate business logic to the server. You can directly make Ajax calls to the API on the server, to do this processing, or you can go with the more sophisticated way and use Flux. There's a plethora of Flux implementations out there, like Alt, Redux and Fluxxor. I prefer to have my own implementation of Flux using the default Dispatcher. Within the ActionCreators
I call a method on the clientApi
(a JS module), which does an Ajax call using Axios to the server. This call is handled by an Express route which finally delegates the business logic to the serverApi
.
EDIT: I just moved to Redux :)
You can push logic inside every class Component and the App Component. Logic in class Component for this state and Logic in App Component for all Application