<?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 Omri levi on Medium]]></title>
        <description><![CDATA[Stories by Omri levi on Medium]]></description>
        <link>https://medium.com/@omril_15649?source=rss-817b69a50c32------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*y01r4Kp8x7X71PHHnPiHYg.png</url>
            <title>Stories by Omri levi on Medium</title>
            <link>https://medium.com/@omril_15649?source=rss-817b69a50c32------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 10:08:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@omril_15649/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[How to manage forms natively in React 19]]></title>
            <link>https://medium.com/@omril_15649/replacing-react-hook-form-in-react-19-dd069f29d505?source=rss-817b69a50c32------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd069f29d505</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook-form]]></category>
            <category><![CDATA[forms]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Omri levi]]></dc:creator>
            <pubDate>Tue, 09 Apr 2024 16:14:17 GMT</pubDate>
            <atom:updated>2024-04-14T13:18:19.795Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*In_AQrTEXImkCk_Ep5Mn6Q.png" /></figure><p>React 19 is on its way with some cool updates. Though we won’t be getting the new compiler <strong>yet</strong>, the React team is introducing some new form management hooks (that are already utilized in Next.js 14) called useFormState and useFormStatus</p><p>We’re here to explore a native alternative to the widely used react-hook-form,so if you&#39;re itching to streamline your form game in React&#39;s newest environment, stick around. We&#39;re going to set up a project, build a custom useForm hook, and play around with dynamic fields and submission states. Let’s get started!</p><h3>Project setup</h3><p>For simplicity, we’ll use Vite to bootstrap the project and install all required dependencies. As the first step, use Vite to initialize a new react project:</p><pre>npm create vite@latest</pre><p>Vite will then ask you to select a framework. Select React and after that TypeScript when prompted to select a variant.</p><p>Now that the project is initialized, let’s install the required dependencies with the command:</p><pre>npm install </pre><p>We’ll need to switch to React’s Canary channel to access the latest Hooks, run this line in the terminal:</p><pre>npm install react@canary react-dom@canary</pre><p>We’ll also adjust our TypeScript configuration to align with these Canary versions. To do so, go to vite-env.d.ts and change the contents of that file to the following:</p><pre>/// &lt;reference types=&quot;vite/client&quot; /&gt;<br>/// &lt;reference types=&quot;react/canary&quot; /&gt;<br>/// &lt;reference types=&quot;react-dom/canary&quot; /&gt;</pre><p>Once everything is installed, a quick npm run dev will get our development server running:</p><pre>npm run dev</pre><p>This will start the React server. You should see the following screenshot in your browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LeLb3MBGeTeZDjP_o62Fyg.png" /></figure><h3>Getting started with our project</h3><p>Now it’s time to write some code. We’ll start simple: a form component that gathers user input. Think of a classic contact form. It will have a few input fields (like name, email) and a submit button. Here, we’re building the foundation for our custom hook, setting the stage to incorporate the beloved functionalities of react-hook-form later on.</p><h3>Building our contact form</h3><p>First things first, we need to create a simple form component with two fields — user and email. Create a file called contact-form.tsx and paste the following code:</p><pre>// contact-form.tsx<br>import React from &quot;react&quot;;<br><br>const ContactForm: React.FC = () =&gt; {<br>  return (<br>      &lt;form&gt;<br>        &lt;input name=&quot;name&quot; /&gt;<br>        &lt;input name=&quot;email&quot; /&gt;<br>        &lt;input type=&quot;submit&quot; /&gt;<br>      &lt;/form&gt;<br>  );<br>};<br><br>export default ContactForm;<br>// Note: Please remember to import this component in your App.js</pre><h3>Adding React’s useFormState</h3><p>At this stage, we have a basic form that is self managed. Now it’s time to add the new useFormState hook and see how it works together.</p><p>The useFormState hook in React is designed to manage form state efficiently. It takes a function (fn) and an initialState as parameters. fn is executed upon form submission or button press, receiving the previous state and any form action arguments. initialState sets the initial form state, which is updated based on fn&#39;s return value. In this article we won’t be covering server side or server components functionality, and will only handle client side validations.</p><pre>const [state, formAction] = useFormState(fn, initialState);</pre><p>Let’s copy the code above and start to implement it into our ContactForm component.</p><pre>// contact-form.tsx<br>import React from &#39;react&#39;;<br>import { useFormState } from &#39;react-dom&#39;;<br><br>interface FormState {<br>  name: string;<br>  email: string;<br>}<br><br>const handleSubmit = async (<br>  previousState: FormState | undefined,<br>  formData: FormData<br>): Promise&lt;FormState&gt; =&gt; {<br>  // The previousState variable contains the last saved form state<br>  console.log(&#39;previous saved state &#39;, previousState);<br>  // Use get to extract a value from a FormData object<br>  const name = formData.get(&#39;name&#39;);<br>  const email = formData.get(&#39;email&#39;);<br>  // The returned value will become our new formState<br>  return { name, email };<br>};<br><br>const ContactForm: React.FC = () =&gt; {<br>  const [formState, formAction] = useFormState(handleSubmit, {<br>    name: &#39;&#39;,<br>    email: &#39;&#39;,<br>  });<br><br>  return (<br>    &lt;&gt;<br>      formState: {JSON.stringify(formState)}<br>      &lt;form action={formAction}&gt;<br>        &lt;input name=&#39;name&#39; /&gt;<br>        &lt;input name=&#39;email&#39; /&gt;<br>        &lt;input type=&#39;submit&#39; /&gt;<br>      &lt;/form&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default ContactForm;</pre><p>Here’s an explanation of the code block above:</p><ul><li>We pass a handler function called handleSubmit which receives two parameters — the old form state, and the new form values as a FormData object. the value it returns becomes the new form state, in our case the submitted name and email, however we can return everything we want, for example a status indication of success or failure, or a message to show to the user.</li><li>A second parameter with initial state with empty name and email properties. To be clear their values will not be passed down as initial values to the appropriate field</li><li>As a result, useFormState will now return two variables: formState, and formAction which we attach to our form like so: &lt;form action={formAction}&gt; and will be executed on submit (in our case we’ll use it like onSubmit property).</li><li>Let’s view what is printed by JSON.stringify(formState) before and after submit:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*jg36zJsAesmseFJcpGp0Hg.gif" /></figure><h3>Creating a custom useForm hook</h3><p>Now it’s time to take our spaghetti code above and turn it into a generic reusable hook.</p><p>Create a file called use-form.tsx . Let’s break the following code down:</p><ul><li>useForm function receives a handleSubmit function that gets invoked just like before, and an initial state. For Typescript reusability we’re passing in the type T.</li><li>Since formData is difficult to work with we’re going to make it more manageable by converting it to an object.</li><li>onSubmit function is connected to our useFormState hook, and after manipulating (and later on validating) our data, invokes the handleSubmit function the user provides.</li><li>I’ve also added a submitCount property which we increment each time the onSubmit function is called.</li></ul><pre>// use-form.tsx<br>import { useState } from &#39;react&#39;;<br>import { useFormState, useFormStatus } from &#39;react-dom&#39;;<br><br>interface FormProps&lt;T&gt; {<br>  formAction: () =&gt; void;<br>  pending: boolean;<br>  formState: T;<br>  submitCount: number;<br>}<br><br>function useForm&lt;T&gt;(<br>  handleSubmit: (data: T) =&gt; void,<br>  initialState: T<br>): FormProps&lt;T&gt; {<br>  const [formState, formAction] = useFormState&lt;T&gt;(onSubmit, initialState);<br>  const { pending } = useFormStatus();<br>  const [submitCount, setSubmitCount] = useState(0);<br><br>  async function onSubmit(previousState: T, formData: FormData): Promise&lt;T&gt; {<br>    setSubmitCount((count) =&gt; count + 1);<br>    const fieldValues = Object.fromEntries(formData) as T;<br>    await handleSubmit(fieldValues);<br>    return fieldValues;<br>  }<br><br>  return {<br>    formAction,<br>    pending,<br>    formState,<br>    submitCount,<br>  };<br>}<br><br>export default useForm;</pre><p>Now let’s import our useForm inside our ContactForm component:</p><pre>// contact-form.tsx<br>import React from &#39;react&#39;;<br>import useForm from &#39;./use-form&#39;;<br><br>interface FormState {<br>  name: string;<br>  email: string;<br>}<br><br>const handleSubmit = async (<br>  data: FormState // formData is now a regular data<br>) =&gt; {<br>// here we can interact with the server or do our own check of the data<br>  console.log(&#39;formData&#39;, data);<br>};<br><br>const ContactForm: React.FC = () =&gt; {<br>  const { formState, formAction } = useForm&lt;FormState&gt;(handleSubmit, {<br>    name: &#39;&#39;,<br>    email: &#39;&#39;,<br>  });<br><br>  return (<br>    &lt;&gt;<br>      formState: {JSON.stringify(formState)}<br>      &lt;form action={formAction}&gt;<br>        &lt;input name=&#39;name&#39; /&gt;<br>        &lt;input name=&#39;email&#39; /&gt;<br>        &lt;input type=&#39;submit&#39; /&gt;<br>      &lt;/form&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default ContactForm;</pre><p>Currently handleSubmit doesn’t do too much, you can add server-side validation or manipulate the data to return a new state.</p><h3>Adding register function</h3><p>Now I’m sure you’re telling yourself, what if I want real-time form validation and display feedback to the user before submitting the form.</p><p>react-hook-form has a cool method called register which accepts a field name and adds onChange , onBlur and name properties to the input component. This will allow us to store a touched fields state, validate them in real-time and provide information before form submission.</p><p>We’ll add some local states inside use-form.tsx to store this information, formData is basically a live representation of formState , which we know gets updated only after submit.</p><pre>  const [touched, setTouched] = useState({});<br>  const [formData, setFormData] = useState(initialState);</pre><p>The register function adds onBlur and onChange event handlers:</p><pre><br>// use-form.tsx - inside useForm hook<br><br>  const handleChange = (event: ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>    const { name, value } = event.target;<br>    setFormData((prev) =&gt; ({ ...prev, [name]: value }));<br>  };<br><br>  const handleBlur = (event: ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>    const { name } = event.target;<br>    setTouched((prev) =&gt; ({ ...prev, [name]: true }));<br>  };<br><br>  const register = (name: keyof T) =&gt; ({<br>    name,<br>    onChange: handleChange,<br>    onBlur: handleBlur,<br>  });</pre><p>Now we’ll replace formState with formData, and use the register function instead of passing a nameprop.contact-form.tsx should look like:</p><pre>const ContactForm: React.FC = () =&gt; {<br>  const { formData, register, formAction } = useForm&lt;FormState&gt;(handleSubmit, {<br>    name: &#39;&#39;,<br>    email: &#39;&#39;,<br>  });<br><br>  return (<br>    &lt;&gt;<br>      formState: {JSON.stringify(formData)}<br>      &lt;form action={formAction}&gt;<br>        &lt;input {...register(&#39;name&#39;)} /&gt;<br>        &lt;input {...register(&#39;email&#39;)} /&gt;<br>        &lt;input type=&#39;submit&#39; /&gt;<br>      &lt;/form&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><p>Now formData shows live changes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*PUcKZcn7Nd3QV0AD4gbdtw.gif" /></figure><h3>Adding form validation using Yup</h3><p>yup is a popular schema builder for runtime value parsing and validation. Install it by running this command in the terminal</p><pre>npm install yup</pre><p>Add the necessary validationSchema parameter to useForm and store a local errors state. The validate function will run on form submission and for every field’s onBlur event:</p><pre>// use-form.tsx<br>import { ObjectSchema } from &#39;yup&#39;;<br><br>function useForm&lt;T&gt;(<br>  handleSubmit: (data: T) =&gt; void,<br>  initialState: T,<br>  validationSchema?: ObjectSchema&lt;T&gt;<br>): FormProps&lt;T&gt; {<br>const [errors, setErrors] = useState({});<br><br>  const validate = async (data: T) =&gt; {<br>    let errors = {};<br>    try {<br>      await validationSchema?.validate(data, { abortEarly: false });<br>    } catch (err) {<br>      if (err instanceof ValidationError) {<br>        const newErrors: Record&lt;string, string&gt; = {};<br>        err.inner.forEach((error) =&gt; {<br>          if (error.path) newErrors[error.path] = error.message;<br>        });<br>        errors = newErrors;<br>      }<br>    }<br>    return errors as Record&lt;keyof T, string&gt;;<br>  };<br><br>  async function onSubmit(previousState: T, formData: FormData): Promise&lt;T&gt; {<br>    setSubmitCount((count) =&gt; count + 1);<br>    const fieldValues = Object.fromEntries(formData) as T;<br>    const errors = await validate(fieldValues);<br>    setErrors(errors);<br>    await handleSubmit(fieldValues, errors);<br>    return fieldValues;<br>  }<br><br>  const handleBlur = (event: ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>    const { name, value } = event.target;<br>    if (validationSchema) {<br>      // creating a schema only for the blurred field<br>      const fieldSchema = validationSchema.pick([name]);<br>      fieldSchema<br>        .validate({ [name]: value })<br>        .then(() =&gt; setErrors((currErrors) =&gt; ({ ...currErrors, [name]: &#39;&#39; })))<br>        .catch((err) =&gt;<br>          setErrors((currErrors) =&gt; ({ ...currErrors, [name]: err.message }))<br>        );<br>    }<br>    setTouched((prev) =&gt; ({ ...prev, [name]: true }));<br>  };<br></pre><p>Inside contact-form.tsx let’s add a validationSchema object and pass it as a third parameter to useForm hook. We can import the new errors object from useForm and show errors with errors.name or errors.email like:</p><pre>// contact-form.tsx<br>import * as yup from &#39;yup&#39;;<br><br>const validationSchema = yup.object({<br>  name: yup<br>    .string()<br>    .min(2, &#39;Too short!&#39;)<br>    .max(50, &#39;Too long!&#39;)<br>    .required(&#39;Required&#39;),<br>  email: yup.string().email(&#39;Invalid email&#39;).required(&#39;Required&#39;),<br>});<br><br>const ContactForm: React.FC = () =&gt; {<br>  const { formData, errors, register, formAction } = useForm&lt;FormState&gt;(<br>    handleSubmit,<br>    {<br>      name: &#39;&#39;,<br>      email: &#39;&#39;,<br>    },<br>    validationSchema<br>  );<br><br>  return (<br>    &lt;&gt;<br>      formState: {JSON.stringify(formData)}<br>      &lt;form action={formAction}&gt;<br>        &lt;input {...register(&#39;name&#39;)} /&gt;<br>        {errors.name &amp;&amp; &lt;div className=&#39;error-message&#39;&gt;{errors.name}&lt;/div&gt;}<br>        &lt;input {...register(&#39;email&#39;)} /&gt;<br>        {errors.email &amp;&amp; &lt;div className=&#39;error-message&#39;&gt;{errors.email}&lt;/div&gt;}<br>        &lt;input type=&#39;submit&#39; /&gt;<br>      &lt;/form&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>We can now display validation errors in real time, or if we prefer, only if submitCount is greater than 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*ovbz5EXVHuJyIlZRvr956g.gif" /></figure><h3>Bonus section</h3><p>React also introduced a hook called useFormStatus which gives us access to the current submission status of our form. So, for example, you can get the current method that was used to submit the form- get | post , and the pending status to display a loading spinner and disable the submit button until completion. To do so just add these 2 lines of code to useForm :</p><pre>// use-form.tsx<br>  <br>  const { pending } = useFormStatus();<br><br>  return {<br>    pending,<br>    // rest of props<br>  };</pre><h3>Conclusion</h3><p><a href="https://github.com/lomri123/react-use-form">Here is the source code for the complete project</a>.</p><p>In this article, you’ve learned the fundamentals of React’s new useFormState hook, and built a solid custom hook for you to expand and tailor to your own needs. Integrating Yup for field validations provided us with a powerful pattern for real-time feedback, ensuring our forms are both user-friendly and technically sound. We’ve laid the groundwork for a potential native react-hook-form replacement!</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd069f29d505" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monorepo components generator | Plop]]></title>
            <link>https://medium.com/@omril_15649/monorepo-components-generator-lerna-plop-2aa7f27a597a?source=rss-817b69a50c32------2</link>
            <guid isPermaLink="false">https://medium.com/p/2aa7f27a597a</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[lerna]]></category>
            <category><![CDATA[plop]]></category>
            <category><![CDATA[monorepo]]></category>
            <category><![CDATA[generator]]></category>
            <dc:creator><![CDATA[Omri levi]]></dc:creator>
            <pubDate>Mon, 21 Nov 2022 14:10:19 GMT</pubDate>
            <atom:updated>2022-11-26T11:26:48.553Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, my team was given a task to create a new monorepo containing UI components. The end result was scheduled to have 50+ packages, that would be contributed by multiple developers.</p><p>As early as at the POC stage, we started realizing we are facing an issue.</p><ul><li>Every package requires a configuration setup — Typescript, Webpack, Storybook, and installing package dependencies.</li><li>Our team has coding standards, file hierarchy and overall best practices that we would like to be implemented throughout of our project.</li><li>Writing all of the boilerplate for every package (or sloppily copy-and-pasting) is not only time consuming, it lends itself to error and encourages inconsistency between projects.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f8y2iksTqVmpRUiiIDSiDw.png" /></figure><p>Our solution was adding a generator tool that would bootstrap each new package for the developer—meaning it would create all the necessary boilerplate files a and install the necessary dependencies.</p><p>A generator is like an interactive boilerplate. It speeds up development without bloat, improves the developer experience and encourages consistency from beginning to finished product.</p><p>Plop is a generator tool which allows you to define a set of functions and helpers, alongside a set of templates that would be generated on the fly, either automatically or by answering to some CLI prompts.</p><p>For this article I’ll assume you have a certain understanding of generators, but if not <a href="https://plopjs.com/documentation/#getting-started">this link</a> will help you make sense of the following.</p><p><strong>Enough prologuing, let’s begin with the actual code!</strong></p><p>I am using this excellent <a href="https://baltuta.eu/posts/typescript-lerna-monorepo-the-setup">monorepo setup guide</a> as the base for my project, which produces a React Typescript monorepo, with Lerna + yarn workspaces to handle project dependencies. In case you don’t already have your own monorepo project set up, you can use this one:</p><pre>git clone https://github.com/lomri123/monorepo-component-generator.git</pre><p><strong>1. Install Plop</strong></p><p>We will install Plop as a development dependency within the project. If you’ve not used yarn workspaces before, the <strong>-W</strong> flag signals that this is a shared dependency to be installed in the root <strong>node_modules</strong> folder.</p><p>So, at the root of your project, type the following in the console:</p><pre>yarn add plop -D -W</pre><p><strong>2. Add a ‘plop’ file</strong></p><p>Let’s create a folder at the root of our project, called very originally- plop, and inside we’ll create a <strong>plopfile.mjs</strong> file</p><p>Since we have created a local copy, we need to call Plop via the npm scripts. Add the “generate-component” script to the main <strong><em>package.json</em></strong> file:</p><pre>{  <br>  ...,  <br>  &quot;scripts&quot;: {    <br>    ...,<br>    &quot;generate-component&quot;: &quot;plop component --plopfile &#39;plop/plopfile.mjs&#39;&quot;<br>  },<br>  ...<br>}</pre><p><strong>3. Create the template files</strong></p><p>The templates are simply <a href="https://handlebarsjs.com/"><em>handlebars</em></a><em> </em>files (<em>*.hbs</em>) which, at their most basic level, take a set of variables and transform them into a text output. As the name suggests, the placeholders for each variable appear in the template between <em>{{handlebars}} </em>which then get replaced with supplied values when the script is called.</p><p>We will create eight template files and place them inside a new folder called templates inside our plop folder</p><ul><li>index.ts.hbs</li><li>jest.config.js.hbs</li><li>main-component.tsx.hbs</li><li>package.json.hbs</li><li>stories.mdx.hbs</li><li>styles.ts.hbs</li><li>tsconfig.json.hbs</li><li>types.ts.hbs</li></ul><p>Let’s go over each and every one of the templates:</p><ul><li><strong>index.ts.hbs:</strong></li></ul><p>This will be the main index file for our project, which will just bundle all our exports</p><pre>export * from &#39;./{{kebabCase name}}&#39; <br>export { default } from &#39;./{{kebabCase name}}&#39;</pre><ul><li><strong>jest.js.config.hbs:</strong></li></ul><p>This file is not mandatory and can be replaced with whatever testing library you prefer</p><pre>const base = require(&quot;../../jest.config.base&quot;);<br>const packageJson = require(&quot;./package&quot;);<br><br>module.exports = {<br>  ...base,<br>  rootDir: &quot;./../../&quot;,<br>  name: packageJson.name,<br>  displayName: packageJson.name,<br>};</pre><ul><li><strong>main-component.tsx.hbs:</strong></li></ul><p>Now we’ll create our main react component, enforcing Typescript usage and adding custom selectors that could be used for later tests/debugging</p><pre>import React, { FC, forwardRef } from &#39;react&#39;<br>import { {{pascalCase name}}Props } from &#39;./types&#39;<br><br>const ID = &#39;{{pascalCase name}}&#39;<br><br><br>export const {{pascalCase name}}: FC&lt;{{pascalCase name}}Props&gt; = forwardRef&lt;<br>  HTMLDivElement,<br>  {{pascalCase name}}Props<br>&gt;(({ &#39;data-selector&#39;: dataSelector = ID, className, &#39;aria-label&#39;: ariaLabel }, ref) =&gt; {<br>  return (<br>    &lt;div<br>      className={className}<br>      aria-label={ariaLabel}<br>      data-selector={dataSelector}<br>      ref={ref}<br>    &gt;<br>    {{pascalCase name}} Content<br>    &lt;/div&gt;<br>  )<br>})<br><br>{{pascalCase name}}.displayName = &#39;{{pascalCase name}}&#39;<br><br>export default Object.assign({{pascalCase name}}, {<br>  ID,<br>}) as typeof {{pascalCase name}} &amp; {<br>  ID: string<br>}</pre><ul><li><strong>package.json.hbs:</strong></li></ul><pre>{<br>  &quot;name&quot;: &quot;@monorepo/{{kebabCase name}}&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;private&quot;: true,<br>  &quot;main&quot;: &quot;dist/index.js&quot;,<br>  &quot;types&quot;: &quot;dist/index.d.ts&quot;,<br>  &quot;files&quot;: [<br>    &quot;dist&quot;<br>  ],<br>  &quot;scripts&quot;: {<br>    &quot;build&quot;: &quot;tsc -b&quot;,<br>    &quot;start&quot;: &quot;nodemon --inspect dist/index.js&quot;,<br>    &quot;lint&quot;: &quot;eslint ./src --ext .ts,.tsx&quot;,<br>    &quot;clean&quot;: &quot;rm -rf ./dist &amp;&amp; rm tsconfig.tsbuildinfo&quot;,<br>    &quot;watch&quot;: &quot;tsc -b -w --preserveWatchOutput&quot;<br>  }<br>}</pre><ul><li><strong>stories.mdx.hbs:</strong></li></ul><p>Here we’re generating a uniform structure for our storybook app’s pages</p><pre>import { Canvas, Meta, Story, ArgsTable } from &#39;@storybook/addon-docs&#39;<br>import {{pascalCase name}} from &#39;../&#39;<br><br>&lt;Meta<br>  title=&#39;Components/{{pascalCase group}}/{{pascalCase name}}&#39;<br>  component={ {{pascalCase name}} }<br>/&gt;<br><br>### {{pascalCase name}}<br><br>&lt;Canvas&gt;<br>  &lt;Story name=&#39;Preview&#39; args={ {} }&gt;<br>    &lt;{{pascalCase name}} /&gt;<br>  &lt;/Story&gt;<br>&lt;/Canvas&gt;<br><br>### {{pascalCase name}} Props<br><br>&lt;ArgsTable of={ {{pascalCase name}} } /&gt;</pre><ul><li><strong>styles.ts.hbs:</strong></li></ul><p>The styles file is empty, but we’re still creating it to maintain the project’s structure. We’re basically saying to the developer “if you’re using custom styles, add them to here”</p><ul><li><strong>tsconfig.json.hbs:</strong></li></ul><pre>{<br>  &quot;extends&quot;: &quot;../../../tsconfig.json&quot;,<br>  &quot;compilerOptions&quot;: {<br>    &quot;outDir&quot;: &quot;dist&quot;,<br>    &quot;rootDir&quot;: &quot;src&quot;,<br><br>    &quot;module&quot;: &quot;esnext&quot;,<br>    &quot;target&quot;: &quot;ES2019&quot;,<br>    &quot;lib&quot;: [&quot;dom&quot;, &quot;ES2019&quot;]<br>  },<br>  &quot;include&quot;: [&quot;src&quot;],<br>  &quot;exclude&quot;: [&quot;node_modules&quot;, &quot;src/**/*.spec.ts&quot;, &quot;build&quot;, &quot;dist&quot;]<br>}</pre><ul><li><strong>types.ts.hbs:</strong></li></ul><p>Adding common prop types like aria-label for accessibility and a data-selector for tests and debugging purposes</p><pre>export interface {{pascalCase name}}Props {<br>  className?: string;<br>  &quot;data-selector&quot;?: string;<br>  &quot;aria-label&quot;?: string;<br>}</pre><p><strong>Now it’s time to put everything together</strong></p><p>We’ll start by creating a Plop function, with a generator inside it called “component”</p><pre><br>export default function (plop) {<br>  plop.setGenerator(&quot;component&quot;, {<br> description: &quot;Creating new react components&quot;,<br>    prompts: [],<br>    actions: []<br>  });<br>}</pre><h4><strong><em>prompts</em></strong></h4><p><em>prompts</em> takes an array of <a href="https://github.com/SBoudrias/Inquirer.js/"><em>Inquirer.js</em></a><em> </em>questions. The questions are documented in full <a href="https://github.com/SBoudrias/Inquirer.js/#question">here</a>, however in this example we use:</p><ul><li><em>type — “</em>input”, since we are requesting values for variables</li><li><em>name</em> — the name of the variable used in the templates, i.e. <em>name, type,</em> and <em>tag</em></li><li><em>message</em> — A message to display to the user in the console</li></ul><p>we’ll start by getting the list of groups (parent folders inside packages) and asking the user to choose one for his new component.</p><pre>    prompts: [<br>      {<br>        type: &quot;getGroup&quot;,<br>        name: &quot;group&quot;,<br>        message: &quot;Choose component group&quot;,<br>        source: function (answersSoFar, input) {<br>          return getComponentsList(input);<br>        },<br>      },<br>    ],</pre><p>Here is my implementation to getComponentsList function. It’s a simple filesystem lookup that scans our packages dir and returns all directories inside</p><pre>const { INSTALL_DIR, PWD } = process.env;<br>const pathPostfix = INSTALL_DIR || &quot;packages&quot;;<br>const basePath = PWD || &quot;/&quot;;<br>const compPath = path.resolve(basePath, pathPostfix);<br><br>const getDirList = (path) =&gt; {<br>  return readdirSync(path, { withFileTypes: true })<br>    .filter((dirent) =&gt; dirent.isDirectory())<br>    .map((dirent) =&gt; dirent.name);<br>};<br><br>const groupsList = getDirList(compPath);<br><br>const getComponentsList = (input) =&gt; {<br>  if (!input || input === &quot;&quot;) return groupsList;<br>  return groupsList.filter((group) =&gt; group.includes(input));<br>};</pre><p>Next we’ll prompt the user to enter his component’s name:</p><pre>      {<br>        type: &quot;input&quot;,<br>        message: &quot;Enter component name&quot;,<br>        name: &quot;name&quot;,<br>      },</pre><p>The result for these prompts looks like this:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Fclutteredsorrowfuliberianchiffchaff&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Fclutteredsorrowfuliberianchiffchaff&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FClutteredSorrowfulIberianchiffchaff-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="1228" height="644" frameborder="0" scrolling="no"><a href="https://medium.com/media/2054fcc83a8ccc833c39060f44f38045/href">https://medium.com/media/2054fcc83a8ccc833c39060f44f38045/href</a></iframe><p>** I’m using <a href="https://www.npmjs.com/package/inquirer-autocomplete-prompt">inquirer-autocomplete-prompt</a> for the interactive select component</p><h4><strong>Actions</strong></h4><p>There are several types of built-in actions you can use in your <a href="https://plopjs.com/documentation/#interface-generatorconfig">GeneratorConfig</a>. You specify which type of action (all paths are based on the location of the plopfile), and a template to use.</p><p>I’ve created a validateFields function which runs as soon as the prompts stage is done</p><pre>actions: [<br>      {<br>        type: &quot;validateFields&quot;,<br>      },<br>    ],</pre><p>I then registered an actionType with the corresponding name, which basically checks that the entered name matches our project’s standards</p><pre>  plop.setActionType(&quot;validateFields&quot;, function (answers, config, plop) {<br>    const { group, name } = answers || {};<br>    const nameValid = validateInput(name);<br>    const groupValid = validateInput(group);<br>    if (!nameValid || !groupValid) {<br>      throw new Error(<br>        `[${!nameValid &amp;&amp; &quot;component name&quot;}${<br>          !groupValid &amp;&amp; &quot;, group name&quot;<br>        }}] invalid` // can refer to a conventions url here<br>      );<br>    }<br>    const { status, message } = checkDuplicateComponent(<br>      name<br>        .replace(/([a-z])([A-Z])/g, &quot;$1-$2&quot;)<br>        .replace(/[\s_]+/g, &quot;-&quot;)<br>        .toLowerCase()<br>    );<br>    if (status) {<br>      throw new Error(message);<br>    }<br>    return &quot;fields valid&quot;;<br>  });</pre><p><strong>That’s it for the input part. Now let’s generate the output!</strong></p><pre>      {<br>        type: &quot;add&quot;,<br>        templateFile: &quot;templates/package.json.hbs&quot;,<br>        path: `${compPath}/{{kebabCase group}}/{{kebabCase name}}/package.json`,<br>      },<br>      {<br>        type: &quot;add&quot;,<br>        templateFile: &quot;templates/tsconfig.json.hbs&quot;,<br>        path: `${compPath}/{{kebabCase group}}/{{kebabCase name}}/tsconfig.json`,<br>      },<br>      {<br>        type: &quot;add&quot;,<br>        templateFile: &quot;templates/types.ts.hbs&quot;,<br>        path: `${compPath}/{{kebabCase group}}/{{kebabCase name}}/src/types.ts`,<br>      },<br>      {<br>        type: &quot;add&quot;,<br>        templateFile: &quot;templates/styles.ts.hbs&quot;,<br>        path: `${compPath}/{{kebabCase group}}/{{kebabCase name}}/src/styles.ts`,<br>      },<br>      {<br>        type: &quot;add&quot;,<br>        templateFile: &quot;templates/jest.config.js.hbs&quot;,<br>        path: `${compPath}/{{kebabCase group}}/{{kebabCase name}}/jest.config.js`,<br>      },<br>      {<br>        type: &quot;add&quot;,<br>        templateFile: &quot;templates/index.ts.hbs&quot;,<br>        path: `${compPath}/{{kebabCase group}}/{{kebabCase name}}/src/index.ts`,<br>      },<br>      {<br>        type: &quot;add&quot;,<br>        templateFile: &quot;templates/main-component.tsx.hbs&quot;,<br>        path: `${compPath}/{{kebabCase group}}/{{kebabCase name}}/src/{{kebabCase name}}.tsx`,<br>      },<br>      {<br>        type: &quot;add&quot;,<br>        templateFile: &quot;templates/stories.mdx.hbs&quot;,<br>        path: `${compPath}/{{kebabCase group}}/{{kebabCase name}}/src/stories/{{pascalCase name}}.stories.mdx`,<br>      },</pre><p>Another cool trick is executing a custom script to automatically install project dependencies. We’ll add another action called installDependencies</p><pre>      {<br>        type: &quot;installDependencies&quot;,<br>      },</pre><pre>  plop.setActionType(&quot;installDependencies&quot;, function (answers, config, plop) {<br>    const { name } = answers;<br>    console.log(&quot;installing dependencies&quot;);<br>    const foundationDev = `lerna add typescript --scope=@monorepo/${toKebabCase(<br>      name<br>    )} --dev`;<br>    return exec(`${foundationDev}`)<br>      .then(() =&gt; &quot;dependencies installed successfully&quot;)<br>      .catch((err) =&gt; `error installing dependencies: ${err}`);<br>  });</pre><p>here’s how the second stage looks like:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Fpertinentunsightlyasiantrumpetfish&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Fpertinentunsightlyasiantrumpetfish&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FPertinentUnsightlyAsiantrumpetfish-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="1982" height="560" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea64b110771225cabc2b1401cc42da7e/href">https://medium.com/media/ea64b110771225cabc2b1401cc42da7e/href</a></iframe><p>The complete <strong>plop.mjs </strong>can be found <a href="https://github.com/lomri123/monorepo-component-generator/blob/main/plop/plopfile.mjs">here</a></p><p>Ready for the final result??</p><p>Our own generated component with zero effort (kinda)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*zPiOcSmad-TrQ3NzTojD5w.png" /></figure><p>Link to the repository:</p><p><a href="https://github.com/lomri123/monorepo-component-generator">GitHub - lomri123/monorepo-component-generator: Accompanying repository for a monorepo article</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2aa7f27a597a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>