Presentation vs Container best practices for client-side validation


(Mark Winterbottom) #1

Hey guys,

I’m new here and this is my first post on the forums. I’ve been learning React for a while and I have a question about the best practice for something.

I am building a React app and trying to follow the pattern of separating presentational and container components as described here.

I’m confused as to where client-side validation would sit in this pattern?

For example, if I have the following components:

Presentational

  • InputField (rendering an )
  • LoginForm (rendering a with for username and password)

Container

  • LoginPage (renders the and handles making API request)

My question is, where would client-side form validation fit into this? Would it go into <LoginForm> or should it go in the <LoginForm>?

Appreciate any advice anyone can offer!

Cheers,
Mark


(Jason Sooter) #2

This article will give you some insight:

Validation will generally be in the Container.

Libraries like Formik, React-Final-Form, and Redux-Form also help with this. Even if just looking at them for the types of scenarios you need to handle.


(Mickey Puri) #3

Hi Mark
I would recommend putting client side validation in the LoginForm. The form is able to work out if it is valid or not and so this task does not need to be delegated to a parent component.
Mickey


(Joshua Ihejiamaizu) #4

Think of presentation components as strictly concerned with receiving and rendering props. This makes them easier to test and maintain as well as scale for different use cases.

I pretty much support @JasonSooter’s answer. You can also create a Higher Order Component that takes care of validation and prop passing, so your input components are simply always wrapped in the HoC and remain presentational themselves.


(Mark Winterbottom) #5

Hey all, really appreciate you taking the time to response, your suggestions are really helpful.

I have kept the validation out of the presentation components and put it in the container as suggested by @JasonSooter and @joshuaai. So far it seems a lot cleaner and easier to unit test.

Cheers,
Mark