<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rafael Gadotti Bachovas on Medium]]></title>
        <description><![CDATA[Stories by Rafael Gadotti Bachovas on Medium]]></description>
        <link>https://medium.com/@rbgadotti?source=rss-9144412fbede------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*t9ihcndV5GA6pQdytGQc3Q.jpeg</url>
            <title>Stories by Rafael Gadotti Bachovas on Medium</title>
            <link>https://medium.com/@rbgadotti?source=rss-9144412fbede------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 16:47:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rbgadotti/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Best Code Practices with TypeScript and React]]></title>
            <link>https://medium.com/@rbgadotti/best-code-practices-with-typescript-and-react-483a3e366f63?source=rss-9144412fbede------2</link>
            <guid isPermaLink="false">https://medium.com/p/483a3e366f63</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Rafael Gadotti Bachovas]]></dc:creator>
            <pubDate>Wed, 19 Apr 2023 02:06:57 GMT</pubDate>
            <atom:updated>2023-04-19T02:06:57.445Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ww5eFb2fYgzSP-7j.jpg" /></figure><p>Recently, while reading some articles about <strong>React</strong>, I realized how distant the ideas behind the types used can be. Often, this is ignored because the code is working. But why are there so many different types if they all work? I decided to do some research to clear my doubts and find some solutions to the common problems I encounter in my daily work. Unfortunately, there is very little material on the subject, so I decided to share some patterns that I found, mostly based on the <strong>Typescript</strong> documentation and discussions within Github.</p><h3>Wrapping/Mirroring a HTML Element<a href="https://react-typescript-cheatsheet.netlify.app/docs/advanced/patterns_by_usecase/#wrappingmirroring-a-html-element">​</a></h3><p>One of these problems is when we use an <strong>HTML</strong> element as a basis for creating a component in <strong>React</strong>, either to add new functionality or style to avoid code duplication.</p><blockquote><em>Definitely not </em><em>React.HTMLProps or </em><em>React.HTMLAttributes</em></blockquote><p>That was the message I found right away in the <strong>TypeScript</strong> documentation. Which surprised me because they were the most commonly used types I found in articles and videos on the internet. But why not use them?</p><pre>// DON&#39;T USE<br><br>interface ButtonProps extends React.HTMLProps&lt;HTMLButtonElement&gt; {<br>  specialProp: string;<br>}<br><br>function Button(props: ButtonProps) {<br>  const { specialProp, ...rest } = props;<br>  return &lt;button {...rest} /&gt;;<br>}</pre><p>This is an example from the <strong>TypeScript</strong> documentation itself. However, when we use <strong>React.HTMLProps&lt;HTMLButtonElement&gt;</strong> as an interface, it uses <strong>AllHTMLAttributes</strong> under the hood, which defines all HTML properties and is used for HTML elements where you don’t have a specific tag.</p><p>Instead, I recommend using one of the three recommended types:</p><ul><li>React.ComponentProps&lt;&quot;button&quot;&gt;</li><li>React.ComponentPropsWithRef&lt;&quot;button&quot;&gt;</li><li>React.ComponentPropsWithoutRef&lt;&quot;button&quot;&gt;</li></ul><p>In the first case, we have a button that may or may not have a reference; in the second, a button with a reference; and in the third case, a button without a reference. For this, React’s <strong>ComponentProps</strong> uses the type <strong>JSX.IntrinsicElements</strong>, which returns only the properties of the specified element.</p><p>This solves several problems I encountered, such as codes that needed to define properties that are already part of the original element.</p><h4>Component with either one or the other prop, but never both</h4><p>Another common problem is when a component has either one or the other property, but never both. Instead of using two optional properties or even properties that receive a whole object to define something, we can define two types:</p><pre>type ButtonProps1 = {<br>  foo: string<br>}<br><br>type ButtonProps2 = {<br>  bar: string<br>}<br><br><br>function Button(props: ButtonProps1 | ButtonProps2) {<br>  if(&quot;foo&quot; in props){<br>    return &lt;button className=&quot;foo-style&quot; /&gt;;  <br>  }else{<br>    return &lt;button className=&quot;bar-style&quot; /&gt;;<br>  }  <br>}</pre><p>And now we share the common attributes between the two types:</p><pre>interface ButtonProps extends React.ComponentProps&lt;&quot;button&quot;&gt; {<br>  specialProps: string<br>}<br><br>type ButtonProps1 = ButtonProps &amp; {<br>  foo: string<br>}<br><br>type ButtonProps2 = ButtonProps &amp; {<br>  bar: string<br>}<br><br><br>export function Button(props: ButtonProps1 | ButtonProps2) {<br>  const { specialProps, ...rest } = props<br>  if(&quot;foo&quot; in props){<br>    return &lt;button className=&quot;foo-style&quot; /&gt;;  <br>  }else{<br>    return &lt;button className=&quot;bar-style&quot; /&gt;;<br>  }  <br>}</pre><h4>Component with all props or none</h4><p>For this case, we can use a <strong>Utility Type</strong> called <a href="https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type"><strong>Record</strong></a>. Its structure is <strong>Record&lt;Keys, Type&gt;</strong>, where <strong>Keys</strong> are the keys used and <strong>Type</strong> is the type used in these keys:</p><pre>type Nothing = Record&lt;string, never&gt;;<br><br><br>interface ButtonProps extends React.ComponentProps&lt;&quot;button&quot;&gt; {<br>  specialProps: string<br>  oneMoreProp: string<br>}<br><br>function Button(props: Nothing | ButtonProps) {<br>  if(&quot;specialProps&quot; in props){<br>    return &lt;button className=&quot;foo-style&quot; /&gt;;  <br>  }else{<br>    return &lt;&gt;Nothing&lt;/&gt;;<br>  }  <br>}</pre><p>We use the type <strong>never</strong> to indicate that we don’t accept any value. This is different from void, and you can find some material to better detail this. Now see what happens when we use the component:</p><pre>const Page = () =&gt; (<br>  &lt;&gt;<br>    &lt;Button /&gt; {/* Ok */}<br>    &lt;Button specialProps=&quot;a&quot; /&gt; {/* Error */}<br>    &lt;Button specialProps=&quot;a&quot; oneMoreProp=&quot;b&quot; /&gt; {/* Ok */}<br>  &lt;/&gt;<br>)</pre><p>However, this solution may not be the best for everyone, since nothing prevents an <strong>interface</strong> from receiving {} and not having any attributes. But I personally prefer to have a more verbose code than a beautiful one in several moments. However, we have this alternative:</p><pre>interface ButtonProps extends React.ComponentProps&lt;&quot;button&quot;&gt; {<br>  obj?: {<br>    specialProps: string<br>    oneMoreProp: string<br>  }<br>}<br><br>function Button(props: Nothing | ButtonProps) {<br>  if(props.obj){<br>    return &lt;button className=&quot;foo-style&quot; /&gt;;  <br>  }else{<br>    return &lt;&gt;Nothing&lt;/&gt;;<br>  }  <br>}<br><br>const Page = () =&gt; (<br>  &lt;&gt;<br>    &lt;Button /&gt; {/* Ok */}<br>    &lt;Button obj={{specialProps: &quot;a&quot;}} /&gt; {/* Error */}<br>    &lt;Button obj={{specialProps: &quot;a&quot;, oneMoreProp: &quot;b&quot;}} /&gt; {/* Ok */}<br>  &lt;/&gt;<br>)</pre><p>Another solution is to make both properties optional and validate if all of them are being passed, but depending on the component size I think this can become a problem.</p><h4>Passing a prop only if another one is passed</h4><p>Using an example from the documentation itself, imagine that you need to create a text component where if the <strong>expanded</strong> property is passed, you also need the <strong>truncate</strong> property. The expected result is as follows:</p><pre>const MyTextComp = () =&gt; (<br>  &lt;&gt;<br>    {/* Utilização correta */}<br>    &lt;Text&gt;not truncated&lt;/Text&gt;<br>    &lt;Text truncate&gt;truncated&lt;/Text&gt;<br>    &lt;Text truncate expanded&gt;truncate-able but expanded&lt;/Text&gt;<br><br>    {/* TS error: Property &#39;truncate&#39; is missing in type &#39;{ children: string; expanded: true; }&#39; but required in type &#39;{ truncate: true; expanded?: boolean | undefined; }&#39;. */}<br>    &lt;Text expanded&gt;truncate-able but expanded&lt;/Text&gt;<br>  &lt;/&gt;<br>);</pre><p>We can implement it as follows:</p><pre>import { ReactNode } from &quot;react&quot;;<br><br>interface CommonProps {<br>  // ...<br>}<br><br>type NoTruncateProps = CommonProps &amp; { truncate?: false };<br><br>type TruncateProps = CommonProps &amp; { truncate: true; expanded?: boolean };</pre><p>We created two interfaces, one for the case where <strong>truncate</strong> is false and another for the case where <strong>truncate</strong> is true. Then, we use the <strong>Typescript</strong> feature called <strong>Function Overloads,</strong> which is basically defining different signatures for the same function:</p><pre>// Function overloads to accept both prop types NoTruncateProps &amp; TruncateProps<br>function Text(props: NoTruncateProps): JSX.Element;<br>function Text(props: TruncateProps): JSX.Element;<br>function Text(props: CommonProps &amp; { truncate?: boolean; expanded?: boolean }) {<br>  const { children, truncate, expanded, ...otherProps } = props;<br>  const classNames = truncate ? &quot;.truncate&quot; : &quot;&quot;;<br>  return (<br>    &lt;div className={classNames} aria-expanded={!!expanded} {...otherProps}&gt;<br>      {children}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Done. Now your component will only accept the <strong>expanded</strong> property if the <strong>truncate</strong> property is provided.</p><p>By using techniques like these, it is possible to make the code more readable and easy to maintain, as well as save time and avoid common mistakes. It is important to remember that the goal of <strong>Typescript</strong> is to serve as a tool to help organize the project and not as another problem to deal with. Try these techniques in your own projects and comment on the problems you face with <strong>Typescript</strong> in <strong>React</strong>.</p><p>Refs:</p><p><a href="https://react-typescript-cheatsheet.netlify.app/docs/advanced/patterns_by_usecase">Useful Patterns by Use Case</a></p><p><a href="https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/basic_type_example">Typing Component Props</a></p><p><a href="https://www.typescriptlang.org/docs/handbook/utility-types.html">Utility Types</a></p><p><a href="https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads">Function Overloads</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=483a3e366f63" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Melhores práticas de código com TypeScript e React]]></title>
            <link>https://medium.com/@rbgadotti/melhores-pr%C3%A1ticas-de-c%C3%B3digo-com-typescript-e-react-8f7d728e1bb?source=rss-9144412fbede------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f7d728e1bb</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Rafael Gadotti Bachovas]]></dc:creator>
            <pubDate>Tue, 18 Apr 2023 17:52:37 GMT</pubDate>
            <atom:updated>2023-04-18T17:52:37.320Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hvy2A8foLBhGipJs.jpg" /></figure><p>Recentemente, enquanto lia alguns artigos sobre <strong>React</strong>, percebi o quão distantes são as ideias dos tipos utilizados. Muitas vezes, isso é ignorado porque o código está funcionando. Mas por que existem tantos tipos diferentes se todos funcionam? Decidi fazer algumas pesquisas para tirar minhas dúvidas e encontrar algumas soluções para os problemas comuns que encontro no meu dia a dia. Infelizmente, há muito pouco material sobre o assunto, então decidi compartilhar alguns padrões que encontrei, a maioria deles baseada na documentação do <strong>Typescript</strong> e discussões dentro do Github.</p><h3><strong>Encapsular ou Espelhar elementos HTML</strong></h3><p>Um desses problemas é quando utilizamos um elemento <strong>HTML</strong> como base para a criação de um componente no <strong>React</strong>, seja para adicionar uma nova funcionalidade ou estilo para evitar a duplicação de código.</p><blockquote>Definitely not React.HTMLProps or React.HTMLAttributes</blockquote><p>Essa foi a mensagem que encontrei logo de cara nas documentações do <strong>Typescript</strong>. O que me surpreende porque foram os tipos mais utilizados que encontrei em artigos e vídeos pela internet. Mas porque não utilizar?</p><pre>// NÃO UTILIZAR<br><br>interface ButtonProps extends React.HTMLProps&lt;HTMLButtonElement&gt; {<br>  specialProp: string;<br>}<br><br>function Button(props: ButtonProps) {<br>  const { specialProp, ...rest } = props;<br>  return &lt;button {...rest} /&gt;;<br>}</pre><p>Esse é um exemplo da própria documentação do <strong>Typescript</strong>. No entanto, quando utilizamos <strong>React.HTMLProps&lt;HTMLButtonElement&gt;</strong> como interface, ela usa <strong>AllHTMLAttributes</strong> por baixo dos panos, que define todas as propriedades HTML e é usado para elementos HTML em que você não possui uma tag específica.</p><p>Em vez disso, recomendo utilizar um dos três tipos recomendados:</p><ul><li>React.ComponentProps&lt;&quot;button&quot;&gt;</li><li>React.ComponentPropsWithRef&lt;&quot;button&quot;&gt;</li><li>React.ComponentPropsWithoutRef&lt;&quot;button&quot;&gt;</li></ul><p>Os nomes falam por si só. No primeiro caso, temos um botão que pode ou não ter uma referência; no segundo, um botão com referência; e no terceiro caso, um botão sem referência. Para isso, o <strong>ComponentProps</strong> do React utiliza o tipo <strong>JSX.IntrinsicElements</strong>, que retorna apenas as propriedades do elemento especificado.</p><p>Isso resolve diversos problemas que encontrei, como códigos que precisavam definir propriedades que já fazem parte do elemento original.</p><h3>Component com uma ou outra propriedade, mas nunca as duas</h3><p>Outro problema comum é quando um componente tem uma ou outra propriedade, mas nunca ambas. Em vez de utilizar duas propriedades opcionais ou até mesmo propriedades que recebem um objeto inteiro para definir algo, podemos definir dois tipos:</p><pre>type ButtonProps1 = {<br>  foo: string<br>}<br><br>type ButtonProps2 = {<br>  bar: string<br>}<br><br><br>function Button(props: ButtonProps1 | ButtonProps2) {<br>  if(&quot;foo&quot; in props){<br>    return &lt;button className=&quot;foo-style&quot; /&gt;;  <br>  }else{<br>    return &lt;button className=&quot;bar-style&quot; /&gt;;<br>  }  <br>}</pre><p>E agora compartilharmos os atributos comuns entre os dois tipos:</p><pre>interface ButtonProps extends React.ComponentProps&lt;&quot;button&quot;&gt; {<br>  specialProps: string<br>}<br><br>type ButtonProps1 = ButtonProps &amp; {<br>  foo: string<br>}<br><br>type ButtonProps2 = ButtonProps &amp; {<br>  bar: string<br>}<br><br><br>export function Button(props: ButtonProps1 | ButtonProps2) {<br>  const { specialProps, ...rest } = props<br>  if(&quot;foo&quot; in props){<br>    return &lt;button className=&quot;foo-style&quot; /&gt;;  <br>  }else{<br>    return &lt;button className=&quot;bar-style&quot; /&gt;;<br>  }  <br>}</pre><h3>Component com todas propriedade ou nenhuma</h3><p>Para esse caso podemos utilizar um <strong>Utility Type</strong> chamado <a href="https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type"><strong>Record</strong></a>. Sua estrutura é <strong>Record&lt;Keys, Type&gt;</strong>, onde <strong>Keys</strong> são as chaves utilizadas e <strong>Type </strong>é o tipo utilizado nessas chaves:</p><pre>type Nothing = Record&lt;string, never&gt;;<br><br><br>interface ButtonProps extends React.ComponentProps&lt;&quot;button&quot;&gt; {<br>  specialProps: string<br>  oneMoreProp: string<br>}<br><br>function Button(props: Nothing | ButtonProps) {<br>  if(&quot;specialProps&quot; in props){<br>    return &lt;button className=&quot;foo-style&quot; /&gt;;  <br>  }else{<br>    return &lt;&gt;Nothing&lt;/&gt;;<br>  }  <br>}</pre><p>Utilizamos o tipo <strong>never</strong> para dizer que não aceitamos valor nenhum. Isso é diferente de void, e você pode encontrar algum material para detalhar melhor isto. Agora veja o que acontece quando utilizamos o componente:</p><pre>const Page = () =&gt; (<br>  &lt;&gt;<br>    &lt;Button /&gt; {/* Ok */}<br>    &lt;Button specialProps=&quot;a&quot; /&gt; {/* Error */}<br>    &lt;Button specialProps=&quot;a&quot; oneMoreProp=&quot;b&quot; /&gt; {/* Ok */}<br>  &lt;/&gt;<br>)</pre><p>No entanto, essa solução pode não ser a melhor para todos, já que nada impede que uma <strong>interface</strong> receba <strong>{}</strong> e não tenha nenhum atributo. Mas eu particulamente prefiro ter um código mais verboso do que bonito em vários momentos. Porém temos esta alternativa:</p><pre>interface ButtonProps extends React.ComponentProps&lt;&quot;button&quot;&gt; {<br>  obj?: {<br>    specialProps: string<br>    oneMoreProp: string<br>  }<br>}<br><br>function Button(props: Nothing | ButtonProps) {<br>  if(props.obj){<br>    return &lt;button className=&quot;foo-style&quot; /&gt;;  <br>  }else{<br>    return &lt;&gt;Nothing&lt;/&gt;;<br>  }  <br>}<br><br>const Page = () =&gt; (<br>  &lt;&gt;<br>    &lt;Button /&gt; {/* Ok */}<br>    &lt;Button obj={{specialProps: &quot;a&quot;}} /&gt; {/* Error */}<br>    &lt;Button obj={{specialProps: &quot;a&quot;, oneMoreProp: &quot;b&quot;}} /&gt; {/* Ok */}<br>  &lt;/&gt;<br>)</pre><p>Outra solução é deixar as duas propriedades opcionais e validar se todas estão sendo passadas, mas dependendo do tamanho do componente acho que isso pode se tornar um problema.</p><h3>Passar uma propriedade somente se outra for passada</h3><p>Utilizando um exemplo da própria documentação, imagine que você precise criar um componente de texto onde se a propriedade <strong>expanded</strong> for passada, você precisa também da propriedade <strong>truncate</strong>. O resultado que esperamos é o seguinte:</p><pre>const MyTextComp = () =&gt; (<br>  &lt;&gt;<br>    {/* Utilização correta */}<br>    &lt;Text&gt;not truncated&lt;/Text&gt;<br>    &lt;Text truncate&gt;truncated&lt;/Text&gt;<br>    &lt;Text truncate expanded&gt;truncate-able but expanded&lt;/Text&gt;<br><br>    {/* TS error: Property &#39;truncate&#39; is missing in type &#39;{ children: string; expanded: true; }&#39; but required in type &#39;{ truncate: true; expanded?: boolean | undefined; }&#39;. */}<br>    &lt;Text expanded&gt;truncate-able but expanded&lt;/Text&gt;<br>  &lt;/&gt;<br>);</pre><p>Podemos implementar da seguinte forma:</p><pre>import { ReactNode } from &quot;react&quot;;<br><br>interface CommonProps {<br>  // ...<br>}<br><br>type NoTruncateProps = CommonProps &amp; { truncate?: false };<br><br>type TruncateProps = CommonProps &amp; { truncate: true; expanded?: boolean };</pre><p>Criamos duas interfaces, uma para o caso em que <strong>truncate</strong> é falso e outra para o caso em que <strong>truncate</strong> é verdadeiro. Em seguida, utilizamos a funcionalidade do <strong>Typescript</strong> chamada <strong>Function Overloads</strong>, que é basicamente definir diferentes assinaturas para uma mesma função:</p><pre>// Function overloads to accept both prop types NoTruncateProps &amp; TruncateProps<br>function Text(props: NoTruncateProps): JSX.Element;<br>function Text(props: TruncateProps): JSX.Element;<br>function Text(props: CommonProps &amp; { truncate?: boolean; expanded?: boolean }) {<br>  const { children, truncate, expanded, ...otherProps } = props;<br>  const classNames = truncate ? &quot;.truncate&quot; : &quot;&quot;;<br>  return (<br>    &lt;div className={classNames} aria-expanded={!!expanded} {...otherProps}&gt;<br>      {children}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Pronto. Agora seu componente só aceitará a propriedade <strong>expanded</strong> se a propriedade <strong>truncate</strong> for informada.</p><p>Ao utilizar técnicas como essas, é possível tornar o código mais legível e fácil de manter, além de economizar tempo e evitar erros comuns. É importante lembrar que o objetivo do <strong>Typescript</strong> é servir como uma ferramenta de auxílio na organização do projeto e não como mais um problema para lidar. Experimente essas técnicas em seus próprios projetos e comente quais os problemas que você enfrente com <strong>Typescript</strong> no <strong>React</strong>.</p><p>Links úteis:</p><p><a href="https://react-typescript-cheatsheet.netlify.app/docs/advanced/patterns_by_usecase">Useful Patterns by Use Case</a></p><p><a href="https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/basic_type_example">Typing Component Props</a></p><p><a href="https://github.com/microsoft/TypeScript/issues/47486#issuecomment-1015671856">Discussão sobre objetos vazios no Typescript</a></p><p><a href="https://www.typescriptlang.org/docs/handbook/utility-types.html">Utility Types</a></p><p><a href="https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads">Function Overloads</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f7d728e1bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Form Validation with Zod and React Hook Form: Ensuring Data Integrity for Your Web Forms]]></title>
            <link>https://medium.com/@rbgadotti/form-validation-with-zod-and-react-hook-form-ensuring-data-integrity-for-your-web-forms-823a30c4342c?source=rss-9144412fbede------2</link>
            <guid isPermaLink="false">https://medium.com/p/823a30c4342c</guid>
            <category><![CDATA[zod]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook-form]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Rafael Gadotti Bachovas]]></dc:creator>
            <pubDate>Tue, 18 Apr 2023 05:09:45 GMT</pubDate>
            <atom:updated>2023-04-18T05:45:59.838Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*57Yf4WLEpmfrFYY_.png" /></figure><p><strong>Zod</strong> is a schema validation library that allows you to validate and type input data in your <strong>TypeScript</strong> application. It offers an easy and intuitive way to define and validate object schemas at runtime, helping to ensure that input data meets the defined validation requirements.</p><p>Some of the features offered:</p><ul><li>Define object schemas at runtime</li><li>Validate input data according to these schemas</li><li>Allow creation of complex object schemas with custom types</li><li>Provide a simple and easy-to-use API for defining and validating schemas</li></ul><p>In summary, it is a tool to ensure that your input data meets the defined expectations.</p><p>And the best part is that <strong>Zod</strong> is fully compatible with <strong>React Hook Form</strong>. This means that you can easily add validations to your React forms using both libraries together. This combination can help make form creation and management in your React application easier, faster, and more reliable.</p><p>I’ll skip the part of installing the library and creating test files, and focus on practical examples. The goal is to demonstrate the power of these tools working together. For more details, you can refer to the documentation of each library or leave a comment.</p><h3>Defining data types</h3><pre>import { z } from &quot;zod&quot;<br><br>const createUserFormSchema = z.object({<br>  username: z.string(),<br>  password: z.string(),<br>  confirm_password: z.string()<br>})</pre><p>So far, nothing out of the ordinary: we are creating a schema to validate a user creation form, in which we need to input information such as username, password, and password confirmation. The code is similar to other popular validation libraries like Joi and Yup.</p><p>It’s possible to add validations and customize the error messages generated for each one:</p><pre>import { z } from &quot;zod&quot;<br><br>const createUserFormSchema = z.object({<br>  username: z.string()<br>    .nonempty(&quot;Username is required&quot;)<br>    .regex(/^[A-Za-z]+$/i, &quot;Only letters are allowed&quot;),<br>  password: z.string()<br>    .nonempty(&quot;Password is required&quot;),<br>  confirm_password: z.string()<br>    .nonempty(&quot;Confirm password is required&quot;)<br>})</pre><p>In the case of password validation, we can use the ‘refine’ method to create custom validations. To learn more, you can consult the <a href="https://zod.dev/?id=refine">documentation</a>. But, in summary, the basic structure is as follows:</p><p><strong><em>.refine(validator: (data:T)=&gt;any, params?: RefineParams)</em></strong></p><pre>import { z } from &quot;zod&quot;<br><br>const createUserFormSchema = z.object({<br>  username: z.string()<br>    .nonempty(&quot;Username is required&quot;)<br>    .regex(/^[A-Za-z]+$/i, &quot;Only letters are allowed&quot;),<br>  password: z.string()<br>    .nonempty(&quot;Password is required&quot;),<br>  confirm_password: z.string()<br>    .nonempty(&quot;Confirm password is required&quot;)<br>})<br>.refine(({ password, confirm_password}) =&gt; password === confirm_password, {<br>  message: &quot;Password doesn&#39;t match&quot;,<br>  path: [&quot;confirm_password&quot;]<br>})</pre><p>In the ‘RefineParams’ object, the attributes define the error information to be generated and where this error will be added. In this case, the error will be added to the existing index of the ‘confirm_password’ field, but it is possible to create a new custom key.</p><p>Although not the main idea of this article, if you are using <strong>Zod</strong> in your backend, it is possible to use the ‘parse’ method to validate your object:</p><pre>const data = {<br>  username: &#39;rafaelgadotti&#39;,<br>  password: &#39;pass1234&#39;,<br>  confirm_password: &#39;pass1234&#39;<br>}<br><br>createUserFormSchema.parse(data); // =&gt; [data object]<br>createUserFormSchema.parse(&#39;test&#39;); // =&gt; throws ZodError</pre><p>Not always is ‘throw Error’ welcome in your application, and in some cases, a more friendly response may be better. In this case, it is possible to use the ‘safeParse’ method:</p><pre>createUserFormSchema.safeParse(data); // =&gt; { success: true; data: [object] }<br>createUserFormSchema.safeParse(&#39;test&#39;); // =&gt; { success: false; error: ZodError }</pre><p>You might be wondering why <strong>Zod</strong> is returning the object itself when validation is successful. The answer is another very useful feature of the library: data transformation. Basically, after passing validation, <strong>Zod</strong> can transform your object. This can be useful in various situations. The method is as follows:</p><pre>const stringToNumber = z.string().transform((val) =&gt; val.length);</pre><p>“But now what? You said you were going to show the integration between Zod and React Hook Forms”. So let’s make the magic happen. Since the focus here is on Zod, I will skip some <strong>React Hook Forms</strong> concepts.</p><h3>Form validation: React Hook Forms + Zod</h3><p>Let’s create a basic form (without worrying about styles):</p><pre>import { useForm } from &quot;react-hook-form&quot;<br><br>const CreateUserForm = () =&gt; {<br><br>  const { register, handleSubmit, watch, formState: { errors } } = useForm()<br><br>  const onSubmit = (data:any) =&gt; {<br>    console.log(data)<br>  }<br><br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;Create User Form&lt;/h1&gt;<br>      &lt;form onSubmit={handleSubmit(onSubmit)}&gt;<br>        &lt;div&gt;<br>          &lt;label htmlFor=&quot;username&quot;&gt;Username&lt;/label&gt;<br>          &lt;input {...register(&quot;username&quot;)} /&gt;<br>          {errors.username &amp;&amp; &lt;span&gt;{errors.username.message}&lt;/span&gt;}<br>        &lt;/div&gt;<br>        &lt;div&gt;<br>          &lt;label htmlFor=&quot;password&quot;&gt;Password&lt;/label&gt;<br>          &lt;input {...register(&quot;password&quot;)} /&gt;<br>          {errors.password &amp;&amp; &lt;span&gt;{errors.password.message}&lt;/span&gt;}<br>        &lt;/div&gt;<br>        &lt;div&gt;<br>          &lt;label htmlFor=&quot;confirm_password&quot;&gt;Confirm password&lt;/label&gt;<br>          &lt;input {...register(&quot;confirm_password&quot;)} /&gt;<br>          {errors.confirm_password &amp;&amp; &lt;span&gt;{errors.confirm_password.message}&lt;/span&gt;}<br>        &lt;/div&gt;<br>        &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>      &lt;/form&gt;<br>    &lt;/&gt;<br>  )<br>}</pre><p>This is a basic form where I added error messages, which won’t be displayed because validations haven’t been added yet. However, if you want to test it with <strong>React Hook Forms</strong> validations, you can add them as follows:</p><pre>&lt;input {...register(&quot;username&quot;, { required: true })} /&gt;<br>// ...</pre><p>But that’s not what we want, here we will integrate the form with <strong>Zod</strong> and the first step is what makes <strong>Zod</strong> so special to be used with <strong>Typescript</strong>:</p><pre>type createUserFormData = z.infer&lt;typeof createUserFormSchema&gt;</pre><p>The <strong>infer</strong> method will return an interface with all the definitions based on the data types we use to make our schema. If you check how <strong>createUserFormData</strong> would look like in your IDE, you will get the following result:</p><pre>type createUserFormData = {<br> username: string;<br> password: string;<br> confirm_password: string;<br>}</pre><p>With this, you already get a significant improvement in the organization of your code and avoid situations where you need to update the same information in different parts of the code.</p><p>With our <strong>type</strong> created, let’s pass it to the React Hook Form’s <strong>useForm</strong> to indicate that our form will contain these data types. Add the following code:</p><p>With this definition, when you register an input in your form, React Hook Form will already know which name options are available based on the attribute names in your schema. Let’s see how the <strong>register</strong> looks like now:</p><pre>const register: &lt;&quot;username&quot; | &quot;password&quot; | &quot;confirm_password&quot;&gt;(name: &quot;username&quot; | &quot;password&quot; | &quot;confirm_password&quot;, options?: RegisterOptions&lt;{<br> username: string;<br> password: string;<br> confirm_password: string;<br>}, &quot;username&quot; | &quot;password&quot; | &quot;confirm_password&quot;&gt; | undefined) =&gt; UseFormRegisterReturn&lt;...&gt;</pre><p>Well, we created our <strong>schema</strong>, generated a <strong>type</strong> using <strong>infer</strong>, used this type to inform the form which data <strong>type</strong> we will use, and now we come to the important part, which is validation.</p><p>For validation, we will install the <strong>@hookform/resolvers</strong> package, which will be responsible for associating our schema with <strong>React Hook Form</strong>. To do this, we will inform that Zod is responsible for this validation. Install:</p><pre>npm install @hookform/resolvers</pre><p>Now let’s import the <strong>Zod</strong> resolver and use it in our form’s hook:</p><pre>//...<br>import { zodResolver } from &quot;@hookform/resolvers/zod&quot;<br><br>//...<br>const { <br>  register,<br>  handleSubmit,<br>  watch,<br>  formState: { errors }<br>} = useForm&lt;createUserFormData&gt;({<br>    resolver: zodResolver(createUserFormSchema)<br>})</pre><p>Done! Now, when validating, <strong>React Hook Forms</strong> will use the schema we generated with <strong>Zod</strong> to generate the same objects as always. This can help reduce code in your forms and is easy to integrate into existing forms.</p><p>Code: <a href="https://github.com/rbgadotti/medium-zod-hook-forms">Form Validation with Zod and React Hook Form</a></p><p>Original: <a href="https://medium.com/@rbgadotti/valida%C3%A7%C3%A3o-de-formul%C3%A1rio-com-zod-e-react-hook-form-garantindo-a-integridade-dos-dados-nos-seus-b1802aa329f1">Validação de formulário com Zod e React Hook Form: Garantindo a integridade dos dados nos seus formulários</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=823a30c4342c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Validação de formulário com Zod e React Hook Form: Garantindo a integridade dos dados nos seus…]]></title>
            <link>https://medium.com/@rbgadotti/valida%C3%A7%C3%A3o-de-formul%C3%A1rio-com-zod-e-react-hook-form-garantindo-a-integridade-dos-dados-nos-seus-b1802aa329f1?source=rss-9144412fbede------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1802aa329f1</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[zod]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react-hook-form]]></category>
            <dc:creator><![CDATA[Rafael Gadotti Bachovas]]></dc:creator>
            <pubDate>Tue, 18 Apr 2023 05:09:09 GMT</pubDate>
            <atom:updated>2023-04-18T05:09:09.190Z</atom:updated>
            <content:encoded><![CDATA[<h3>Validação de formulário com Zod e React Hook Form: Garantindo a integridade dos dados nos seus formulários</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RDImujLQiMSFZ9r6tvyjnA.png" /></figure><p><strong>Zod</strong> é uma biblioteca de validação de esquema que permite validar e tipar dados de entrada em sua aplicação <strong>TypeScript</strong>. Ela oferece uma maneira fácil e intuitiva de definir e validar esquemas de objeto em tempo de execução, ajudando a garantir que os dados de entrada atendam aos requisitos de validação definidos.</p><p>Algumas das funcionalidades oferecidas:</p><ul><li>Definir esquemas de objetos em tempo de execução</li><li>Validar dados de entrada de acordo com esses esquemas</li><li>Permitir a criação de esquemas de objeto complexos com tipos personalizados</li><li>Fornecer uma API simples e fácil de usar para definir e validar esquemas</li></ul><p>Em resumo, é uma ferramenta para garantir que seus dados de entrada atendam às expectativas definidas.</p><p>E o melhor de tudo é que o Zod é totalmente compatível com o React Hook Form. Isso significa que você pode facilmente adicionar validações aos seus formulários React usando ambas as bibliotecas em conjunto. Essa combinação pode ajudar a tornar a criação e gerenciamento de formulários no seu aplicativo React mais fácil, rápido e confiável.</p><p>Vou pular a parte de instalação da biblioteca e criação de arquivos para teste, e me concentrar nos exemplos práticos. O objetivo é mostrar o poder dessas ferramentas trabalhando juntas. Para obter mais detalhes, você pode consultar a documentação de cada biblioteca ou deixar um comentário.</p><h3>Definindo os tipos de dados</h3><pre>import { z } from &quot;zod&quot;<br><br>const createUserFormSchema = z.object({<br>  username: z.string(),<br>  password: z.string(),<br>  confirm_password: z.string()<br>})</pre><p>Até aqui, nada fora do comum: estamos criando um esquema para validar um formulário de criação de usuário, no qual precisamos inserir informações como usuário, senha e confirmação de senha. O código é semelhante a outras bibliotecas populares de validação, como Joi e Yup.</p><p>É possível adicionar validações e personalizar as mensagens de erro geradas para cada uma delas:</p><pre>import { z } from &quot;zod&quot;<br><br>const createUserFormSchema = z.object({<br>  username: z.string()<br>    .nonempty(&quot;Username is required&quot;)<br>    .regex(/^[A-Za-z]+$/i, &quot;Only letters are allowed&quot;),<br>  password: z.string()<br>    .nonempty(&quot;Password is required&quot;),<br>  confirm_password: z.string()<br>    .nonempty(&quot;Confirm password is required&quot;)<br>})</pre><p>No caso da validação das senhas, podemos utilizar o método ‘refine’ para criar validações personalizadas. Para saber mais, é possível consultar a <a href="https://zod.dev/?id=refine">documentação</a>. Mas, de forma resumida, a estrutura básica é a seguinte:</p><p><strong><em>.refine(validator: (data:T)=&gt;any, params?: RefineParams)</em></strong></p><pre>import { z } from &quot;zod&quot;<br><br>const createUserFormSchema = z.object({<br>  username: z.string()<br>    .nonempty(&quot;Username is required&quot;)<br>    .regex(/^[A-Za-z]+$/i, &quot;Only letters are allowed&quot;),<br>  password: z.string()<br>    .nonempty(&quot;Password is required&quot;),<br>  confirm_password: z.string()<br>    .nonempty(&quot;Confirm password is required&quot;)<br>})<br>.refine(({ password, confirm_password}) =&gt; password === confirm_password, {<br>  message: &quot;Password doesn&#39;t match&quot;,<br>  path: [&quot;confirm_password&quot;]<br>})</pre><p>No objeto ‘RefineParams’, os atributos definem as informações do erro a ser gerado e onde esse erro será adicionado. No caso, o erro será adicionado ao índice já existente do campo ‘confirm_password’, mas é possível criar uma nova chave personalizada.</p><p>Apesar de não ser a ideia principal deste artigo, se você estiver utilizando o <strong>Zod</strong> no seu backend, é possível utilizar o método ‘parse’ para validar o seu objeto:</p><pre>const data = {<br>  username: &#39;rafaelgadotti&#39;,<br>  password: &#39;pass1234&#39;,<br>  confirm_password: &#39;pass1234&#39;<br>}<br><br>createUserFormSchema.parse(data); // =&gt; [data object]<br>createUserFormSchema.parse(&#39;test&#39;); // =&gt; throws ZodError</pre><p>Nem sempre ‘throw Error’ é bem vindo na sua aplicação e, em alguns casos, pode ser melhor uma resposta mais amigável. Nesse caso, é possível utilizar o método ‘safeParse’.</p><pre>createUserFormSchema.safeParse(data); // =&gt; { success: true; data: [object] }<br>createUserFormSchema.safeParse(&#39;test&#39;); // =&gt; { success: false; error: ZodError }</pre><p>Você pode estar se perguntando por que o <strong>Zod</strong> está retornando o próprio objeto quando a validação é bem-sucedida. A resposta é outra característica muito útil da biblioteca: a transformação de dados. Basicamente, após passar nas validações, o <strong>Zod</strong> pode transformar o seu objeto. Isso pode ser útil em várias situações. Por exemplo, traduzir objetos jsons para outros formatos. O método é o seguinte:</p><pre>const stringToNumber = z.string().transform((val) =&gt; val.length);</pre><p>Fico devendo um artigo apenas sobre transformação de dados…</p><p><em>“Mas e agora? Você disse que ia mostrar a integração entre o Zod e o React Hook Forms”</em>. Vamos então fazer a mágica acontecer. Como o foco aqui é o Zod, vou pular alguns conceitos do <strong>React Hook Forms</strong>.</p><h3>Validação de formulários: React Hook Forms + Zod</h3><p>Vamos criar um formulário básico (não me preocupei com estilos):</p><pre>import { useForm } from &quot;react-hook-form&quot;<br><br>const CreateUserForm = () =&gt; {<br><br>  const { register, handleSubmit, watch, formState: { errors } } = useForm()<br><br>  const onSubmit = (data:any) =&gt; {<br>    console.log(data)<br>  }<br><br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;Create User Form&lt;/h1&gt;<br>      &lt;form onSubmit={handleSubmit(onSubmit)}&gt;<br>        &lt;div&gt;<br>          &lt;label htmlFor=&quot;username&quot;&gt;Username&lt;/label&gt;<br>          &lt;input {...register(&quot;username&quot;)} /&gt;<br>          {errors.username &amp;&amp; &lt;span&gt;{errors.username.message}&lt;/span&gt;}<br>        &lt;/div&gt;<br>        &lt;div&gt;<br>          &lt;label htmlFor=&quot;password&quot;&gt;Password&lt;/label&gt;<br>          &lt;input {...register(&quot;password&quot;)} /&gt;<br>          {errors.password &amp;&amp; &lt;span&gt;{errors.password.message}&lt;/span&gt;}<br>        &lt;/div&gt;<br>        &lt;div&gt;<br>          &lt;label htmlFor=&quot;confirm_password&quot;&gt;Confirm password&lt;/label&gt;<br>          &lt;input {...register(&quot;confirm_password&quot;)} /&gt;<br>          {errors.confirm_password &amp;&amp; &lt;span&gt;{errors.confirm_password.message}&lt;/span&gt;}<br>        &lt;/div&gt;<br>        &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>      &lt;/form&gt;<br>    &lt;/&gt;<br>  )<br>}</pre><p>Este é um formulário básico em que adicionei mensagens de erro, que não serão exibidas porque ainda não foram adicionadas validações. No entanto, se você quiser testá-lo com as validações do <strong>React Hook Forms</strong>, pode adicioná-las da seguinte maneira:</p><pre>&lt;input {...register(&quot;username&quot;, { required: true })} /&gt;<br>// ...</pre><p>Mas não é isso que queremos, aqui vamos integrar o formulário com o <strong>Zod</strong> e o primeiro passo é o que torna o <strong>Zod</strong> tão especial para ser utilizado com <strong>Typescript</strong>:</p><pre>type createUserFormData = z.infer&lt;typeof createUserFormSchema&gt;</pre><p>O método <strong>infer </strong>irá retornar uma interface com todas as definições baseadas nos tipos de dados que utilizamos para fazer nosso schema. Se você verificar como ficaria o valor de <strong>createUserFormData</strong> na sua IDE, irá obter o seguinte resultado:</p><pre>type createUserFormData = {<br>    username: string;<br>    password: string;<br>    confirm_password: string;<br>}</pre><p>Com isso, você já obtém uma melhora significativa na organização do seu código e evita situações em que precisa atualizar as mesmas informações em diferentes partes do código.</p><p>Com nosso <strong>type</strong> criado, vamos passá-lo para o <strong>useForm</strong> do <strong>React Hook</strong> Form para indicar que nosso formulário irá conter esses tipos de dados. Adicione o seguinte código:</p><pre>const { <br>  register,<br>  handleSubmit,<br>  watch,<br>  formState: { errors }<br>} = useForm&lt;createUserFormData&gt;()</pre><p>Com essa definição, quando você for registrar um input no seu formulário, o React Hook Form já saberá quais são as opções de nomes disponíveis, com base no nome dos atributos do seu schema. Vejamos como fica o <strong>register</strong> agora:</p><pre>const register: &lt;&quot;username&quot; | &quot;password&quot; | &quot;confirm_password&quot;&gt;(name: &quot;username&quot; | &quot;password&quot; | &quot;confirm_password&quot;, options?: RegisterOptions&lt;{<br>    username: string;<br>    password: string;<br>    confirm_password: string;<br>}, &quot;username&quot; | &quot;password&quot; | &quot;confirm_password&quot;&gt; | undefined) =&gt; UseFormRegisterReturn&lt;...&gt;</pre><p>Bom, criamos nosso <strong>schema</strong>, geramos um <strong>type</strong> utilizando <strong>infer</strong>, utilizamos esse <strong>type</strong> para informar ao formulário qual tipo de dados iremos utilizar e agora vamos à parte importante, que é a validação.</p><p>Para a validação, vamos instalar o pacote <strong>@hookform/resolvers</strong>, que será responsável por associar nosso <strong>schema</strong> ao <strong>React Hook Form</strong>. Para isso, vamos informar que o Zod é o responsável por essa validação. Instale:</p><pre>npm install @hookform/resolvers</pre><p>Agora vamos fazer a importação do <strong>resolver</strong> do <strong>Zod</strong> e utilizar ele no <strong>hook</strong> do nosso formulário:</p><pre>//...<br>import { zodResolver } from &quot;@hookform/resolvers/zod&quot;<br><br>//...<br>const { <br>  register,<br>  handleSubmit,<br>  watch,<br>  formState: { errors }<br>} = useForm&lt;createUserFormData&gt;({<br>    resolver: zodResolver(createUserFormSchema)<br>})</pre><p>Pronto! Agora, ao fazer a validação, o <strong>React Hook Forms</strong> irá utilizar o <strong>schema</strong> que geramos com <strong>Zod</strong> para gerar os mesmos objetos de sempre. Isso pode ajudar a reduzir o código dos seus formulários e é fácil de integrar em formulários já existentes.</p><p>Código completo: <a href="https://github.com/rbgadotti/medium-zod-hook-forms">Form Validation with Zod and React Hook Form</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1802aa329f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>