02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

Validating Development Props

Validating Development Props in React: Updated for 2024

When building reusable React components, prop validation ensures that developers pass the correct types and values, reducing runtime errors and improving code maintainability. While React's prop-types library remains a valid solution, alternative approaches have emerged to suit modern workflows.


Why Validate Props?

  1. Debugging Aid: Validation errors provide immediate feedback, making it easier to spot bugs during development.
  2. Component Reusability: Validations ensure components can handle different data types consistently.
  3. Self-Documentation: Prop validation serves as documentation for developers, showing what data each component expects.

Approach 1: Prop-Types (Traditional)

React's prop-types library is easy to use and perfect for small to medium-sized projects:

  1. Install prop-types
    If your project doesn't include prop-types, install it via npm:

    npm install prop-types
    
  2. Setup Example

    import PropTypes from 'prop-types';
    import React from 'react';
    
    class TextFooter extends React.Component {
      static propTypes = {
        title: PropTypes.string.isRequired,
        content: PropTypes.node.isRequired,
      };
    
      static defaultProps = {
        title: 'Default Title',
        content: 'Default Content',
      };
    
      render() {
        const { title, content } = this.props;
        return (
          <div>
            <h3>{title}</h3>
            <p>{content}</p>
          </div>
        );
      }
    }
    
    export default TextFooter;
    
  3. Advanced Features

    • Validate specific sets of values using PropTypes.oneOf():
      size: PropTypes.oneOf(['small', 'medium', 'large']),
      
    • Validate object shapes with PropTypes.shape():
      user: PropTypes.shape({
        name: PropTypes.string.isRequired,
        age: PropTypes.number,
      }),
      

Approach 2: TypeScript (Recommended for 2024)

For modern React projects, TypeScript is the preferred choice for static type checking. Unlike prop-types, TypeScript performs validations at compile time, not runtime, offering a robust development experience.

  1. Why TypeScript?

    • Static Validation: Errors are caught before code execution.
    • IDE Support: Enhanced auto-completions and error hints.
    • Team Scalability: Large teams benefit from strongly typed contracts.
  2. Setup Example

    type TextFooterProps = {
      title: string;
      content: React.ReactNode;
    };
    
    const TextFooter: React.FC<TextFooterProps> = ({ title, content }) => (
      <div>
        <h3>{title}</h3>
        <p>{content}</p>
      </div>
    );
    
    TextFooter.defaultProps = {
      title: 'Default Title',
      content: 'Default Content',
    };
    
    export default TextFooter;
    
  3. Key Advantages Over Prop-Types

    • Compile-time validation ensures errors are addressed before runtime.
    • Eliminates the need for external libraries like prop-types.
    • Supports complex and nested data types natively.

Approach 3: Zod or Yup for Runtime Validation

For projects requiring runtime validation (e.g., dynamic data fetched from APIs), libraries like Zod or Yup can provide schema-based validation.

  1. Why Use Zod or Yup?

    • Ideal for validating API responses or user inputs.
    • Supports complex and nested validation rules.
    • Works seamlessly with TypeScript for type-safe validation.
  2. Setup Example with Zod

    import { z } from 'zod';
    
    const TextFooterSchema = z.object({
      title: z.string(),
      content: z.string().or(z.element()), // Allows either string or JSX elements
    });
    
    const validateProps = (props) => {
      const result = TextFooterSchema.safeParse(props);
      if (!result.success) {
        console.error('Invalid props:', result.error);
      }
    };
    
    const TextFooter = (props) => {
      validateProps(props);
      const { title, content } = props;
      return (
        <div>
          <h3>{title}</h3>
          <p>{content}</p>
        </div>
      );
    };
    
    export default TextFooter;
    

Comparing Approaches

FeatureProp-TypesTypeScriptZod/Yup
Validation TypeRuntimeCompile-TimeRuntime
Ease of SetupEasyModerateModerate
IntegrationNative to ReactTypeScript EcosystemExternal Libraries
Performance ImpactMinimalNoneMinimal
Complex Schema SupportLimitedExcellentExcellent

Best Practices in 2024

  1. Small Projects: Use prop-types for simplicity.
  2. TypeScript-First: For modern, scalable projects, TypeScript is the go-to choice.
  3. Runtime Needs: For dynamic validation (e.g., API data), pair TypeScript with Zod or Yup.
  4. Consistency: Choose one approach and standardize it across the project to maintain codebase consistency.

Conclusion

Prop validation is essential for reusable React components. While prop-types remains viable, TypeScript is now the recommended approach for most projects due to its compile-time checks and strong typing. For runtime validation, libraries like Zod or Yup offer a flexible, schema-based solution. Choose the method that best suits your project's complexity and team needs.

Video Transcript

00:01Validating properties is probably the most important thing
00:04when you're creating components that are gonna be used
00:07by others and even yourself
00:09as you look at components you didn't touch for a long time.
00:12So the more validators you have, the better.
00:14And in this lecture we're gonna learn on the built in way
00:17you could add those type of validations
00:19that would only trigger overhead in the development
00:22version of React.
00:25Alright, let's continue
00:26and fulfill our promise from the last lecture.
00:29And really what we wanna do is we want
00:31to create some validation of content to be able
00:34to give an error if the content is not valid.
00:37And to do that the most easy way to do then by the way,
00:40this errors will only appear in development,
00:43not in production, which is really wonderful.
00:45It's only in the development version of React.
00:48If we go ahead into our element that we want to,
00:51let's say we want to validate our text footer to make sure
00:54that the title that's coming in is of a certain type
00:57and then the content coming in here is of a certain type.
01:00Now the way we would do that is uh,
01:02learn another new E es six thing.
01:05Now generally speaking in E es six, there is no way
01:08to just add properties directly.
01:10There's no this dot whatnot, this dot whatnot.
01:14The way you would do that is create a constructor,
01:16which we've done that already previously a few times,
01:19and add into the properties by you creating the constructor.
01:23And let me see if we, we should have a constructor already
01:26created, maybe in the header, maybe in the portfolio.
01:30There we goes. And our constructor,
01:31we just created those properties.
01:33So those were properties of our class.
01:36Now how do you create a static property?
01:39There's two main ways to do that.
01:41One way to do that in ES six is if I wanted
01:44to create a static property, I could,
01:45after the creation of the class that has a name, I could go
01:49and say text foot footer.
01:51A version equals 1.01.
01:56Let's say whenever I would wanna refer to
01:59that text input version,
02:00I would just call the full qualified name.
02:03So I would do a console, console log
02:08and then just output that version.
02:13Our text
02:18Is Version
02:23and if I go ahead and run it, we'll see
02:24that we'll get here in our output that our text version is
02:28and that property name.
02:29So that is our static property that belongs
02:31to the class overall.
02:34Now for react, to react to the components
02:37that we're creating in E Es X, we need
02:39to send in a static property with the name of prop types.
02:43Now I'm gonna show you another way of doing it
02:45besides setting it after the creation
02:47of the component right inside.
02:49Now in E ES six, this is how we would do it.
02:52I would start with the declaration of static.
02:55Now I cannot create properties directly.
02:57So instead of that I'm create, I'm gonna create a getter
03:00and I'm gonna go ahead into my prop types,
03:04which is the item that I want to create.
03:06And I'm literally creating that method
03:08and I'm gonna return the item that I wanna return.
03:12So in this case, I'm creating a static, it's gonna be
03:15accessible through text, footer dot prop types.
03:18And then here I would send in the value
03:20that is expected by the component.
03:23Okay? Now by the way, setters work the same way.
03:26So in this case I'm getting that value.
03:28But if I wanted to set a VA a value that's inside,
03:31I would call it set and then use a function to do so.
03:34Okay? But in our case, we're only gonna address a getter.
03:37And in this stage I really just want to get a value.
03:40And this value doesn't have to be built inside.
03:42So I'm just gonna create a getter.
03:44And what I'm gonna do is I'm gonna list out the variables
03:46such as the title that I have here.
03:48And also we're gonna do the content
03:50that we're expecting from the properties.
03:52And then I'm just gonna go to my react dot
03:56prop in uppercase types dot the type that I want.
04:01There's a quite a lot of different types.
04:03Let's for example, I'm gonna do number now,
04:05number is gonna make sure that the value
04:07of title must be a number.
04:09Now what's gonna happen is
04:10because I've set these prop types,
04:11if I run my application again, we're gonna get an error.
04:14And if we find that error,
04:16we're rendering a component though, that's fine.
04:19And here we go, failed prop, invalid prop,
04:21blah blah blah, blah, blah.
04:22It's expecting, uh, te, it's expecting a number
04:26but it got a text footer, um, blah blah blah blah blah.
04:29But in our case, really we really wanna send text here.
04:32So I'm gonna make sure that this is a string.
04:34Now I'm gonna go ahead and also for our content,
04:36I wanna declare that, I wanna make sure
04:38that this is actually a visible item
04:41or an item that could be visible.
04:43And to do that, I'm gonna call here node
04:45and node per se says
04:46that whatever value I'm getting here could be
04:48outputted directly onto the stage.
04:50'cause with our text footer,
04:51that's exactly what we're doing.
04:53We're rendering it, we're assuming
04:54that the content is renderable.
04:56Now if I go ahead and I save this
04:58and go back into my application
05:00and look at the values that I'll get here, first of all,
05:02I'm not getting any errors
05:04'cause really all the values that I'm
05:05sending are renderable.
05:06But beyond that, if I send now for example,
05:09and I activate our Vista props for our item here,
05:13that is not gonna be valid
05:15because we have their an array that we're sending in.
05:17Then this time around we're also gonna get an error
05:19that will help our developers that are working.
05:22We're gonna get an error telling us,
05:23by the way you've been sending here, uh, not sending
05:26what we're expecting into the content.
05:28So it's making it a lot easier for developers
05:30to then understand what is the error that they need
05:32to address and they need to take care of.
05:35So that is in essence how you work with
05:39those validators.
05:41Now I wanna show you just one more
05:43'cause there's a lot of different types of validators.
05:45What would happen in a situation
05:47where you would want your text, for example, in the title
05:50to be aura type string or a number, but nothing but that.
05:54Now, the way you would do that is that,
05:55I'm gonna go ahead here and just start
05:57up another prop types.
05:58This time I'm gonna call a method of one of,
06:02and it expects an array by the way.
06:04One of is a method as well.
06:05We could list out exactly the values you expect.
06:07But in this TA case, I want a one of type
06:10and I'm gonna go ahead and then send an array.
06:12If I manage to find the right bracket,
06:15I'm gonna send an array and that array will have a string
06:19and that array could have O2, let's say a number.
06:24And I could close that baby up, close that array up, close
06:28that bracket up, put a comma
06:30because we're done, done with it.
06:32And then it's gonna validate that it could be,
06:34or a string or a number.
06:36In this case, everything should continue working.
06:38So once we go through our refresh,
06:41let's see if we have here an error, what is our error?
06:44React default props. One of types not function.
06:47That is because it's one of type, not one
06:49of types, one of type.
06:52Save refresh. And okay, let's see.
06:56Warning, failed property and valid property con, right?
06:59The why is it failing? Because in our item below right here,
07:03we're still sending in values that are not valid.
07:05So lemme go ahead here and just not
07:07put anything in just for this one.
07:09We'll put it empty and if we run it, we'll see
07:11that now everything is running again.
07:13In the next lecture we're gonna go back into
07:15that one less item that's left here
07:17and I'm gonna put it back so that error will appear
07:19and then figure out how do we render it
07:21and render that variation of it, which
07:23by the way would not be a text input,
07:25but we would want to use our complex text footer
07:29and obviously change the logic here.
07:31So this logic is dynamic as well.
07:33But for now, let me go ahead here
07:34and I'll just put it at our complex footer
07:36that really just to put that item there.
07:38And in the next lecture we'll turn this baby into
07:40something dynamic as well.
07:42In this lecture we saw how
07:43to validate development properties to give more feedback
07:47for the developers that are working with our components.
07:50In the next lecture we're gonna talk about
07:52more dynamic things.
07:54'cause really everything is about making content dynamic.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!