Tarun Dugar
Tarun Dugar

Reputation: 8971

Where to write logic related to component that doesn't affect the UI directly

I have a component which contains a textarea. Whenever I enter text I run a set of validations against the text and depending upon results I update the UI. You can assume the code to be like this:

onTextChange(e) {
    const results = this.runValidations(e.target.value)
}

Now, the problem is this.runValidations is like 100 lines of code sitting right there in the component but doesn't affect the UI directly and is specific only to the component and its child components. But, it makes my component file bloated.

So, is there any convention that other people follow in their React-Redux apps to handle such logical code that is specific to the component but is not part of the UI logic? Where do they place such code?

Upvotes: 1

Views: 160

Answers (2)

Chris
Chris

Reputation: 58182

At the end of the day, most business logic doesn't have a lot to do with React/Redux - so they can usually be shovelled out into their own utility functions or classes. Which is great for a few reasons

  • a) easier to test because it hasn't zero linkage to React/Redux and
  • b) keeps your actions light, and
  • c) more encapsulated - having minimal knowledge of react/redux is not a bad thing.

It's all just Javascript - there is nothing wrong with importing custom business classes or utility functions.

Edit

My folder structure will typically look like:

  • my-component
    • child-components
      • Child1.js
      • _Child1.scss
      • Child2.js
      • _Child2.scss
    • helpers
      • util1.js // with a single default export
      • util2.js // with a single default export
    • _MyComponent.scss
    • MyComponent.js
    • MyComponent.spec

Where child components are (or should) only be pulled into this component. Ie. they shouldn't be used by other components.

This hashnode article also has a great structure if you are using redux as well: hashnode.com/post/tips-for-a-better-redux-architecture-lessons-for-enterprise-scale-civrlqhuy0keqc6539boivk2f

Upvotes: 2

It seems that you are missing the concept of components vs containers (or dumb components vs smart components, as some like to name it). Basically, it is a good practice to apart your business logic from you pure presentational components.

Have a look at Presentational and Container Components, by Dan Abramov.

Upvotes: 0

Related Questions