How to generate react components automatically

Rafael Martins20 Feb 2024

Introduction

In the ever-evolving web development landscape, efficiency and consistency are key factors in maintaining a streamlined workflow. When working on large-scale React.js projects, creating new components can become repetitive and time-consuming. To alleviate this challenge, developers often turn to automation tools that allow for the automatic generation of files. This article explores various methods and tools available for this purpose, providing a step-by-step implementation guide. By leveraging these techniques, developers can enhance their productivity, ensure code consistency, and focus on the creative aspects of building robust React applications. Let’s dive into the automatic component file generation world in React.js and uncover the tools and strategies that can revolutionize your development process.

Tools

Now, let’s delve into the tools that can facilitate automatic React component generation:

In summary, choosing between Yeoman and Plop.js depends on the specific needs and preferences of the developer or team. Yeoman is a feature-rich and opinionated tool that excels in providing a standardized and comprehensive scaffolding experience. Plop.js, on the other hand, is lightweight and flexible, allowing developers to create custom generators tailored to their specific requirements.

Yeoman

Yeoman is a robust and widely adopted scaffolding tool that provides a generator ecosystem for quickly setting up project structures. It comes with a vast array of generators for various frameworks and languages, allowing developers to kick-start projects with pre-configured templates. Yeoman offers a standardized and opinionated approach to project scaffolding, making it suitable for teams or projects that prefer a well-defined structure and conventions.

Use cases

To get started with Yeoman, first, install it globally using the command:

npm install -g yeoman

Choose a generator library, for instance: generator-modern-react that I designed for modern React applications, and install it using:

npm install -g generator-modern-react

Once installed, generate components effortlessly by running:

yo modern-react:componnet --ts

This command generates the component file, the associated styles, and a test file.

Terminal recording

Generated Component Example:

import React from 'react';
import './style.css';

interface FooProps {
}

const Foo: React.FC<FooProps> = () => {
  return (
    <>

    </>
  );
};

export default Foo;

To share this capability with your team, consider adding a script to your package.json:

Run:

npm install yeoman generator-modern-react

and add this script to your package.json:

{
  "scripts": {
    "generate:component": "yo modern-react:component $npm_config_name --ts"
  },
}

Then, components can be generated using:

npm run generate:component foo

For additional use cases and detailed instructions, please refer to the documentation in the generator-modern-react repository.

Plopjs

On the other hand, Plop.js is a lighter and more flexible alternative. It focuses on simplicity and allows developers to create custom generators using a minimalistic API. Plop.js is particularly beneficial for developers who want a more hands-on approach to project setup and desire greater control over the generated code. It is lightweight and can be integrated seamlessly into existing projects without imposing a specific structure, making it a good choice for those who prioritize customization and simplicity.

Use cases

To use Plop.js, create a plopfile.js to index your generators, defining the paths and configurations for each generator.

const projectPath = `${process.cwd()}/src`;

const generators = [
  require("./generators/ClassComponent")(projectPath),
  require("./generators/FunctionalComponent")(projectPath)
];

module.exports = plop => {
  generators.map(g => plop.setGenerator(g.name, g.generator));
};

Set up your generator files, such as ClassComponent.js, specifying the prompts and actions for component generation.

module.exports = projectPath => {
  const cwd = process.cwd()

  const basePath = `
    ${projectPath}/\{{ componentType }}s/\{{ pascalCase name }}
  `

  return {
    name: "ClassComponent",
    generator: {
      description: "Create components",
      prompts: [
        {
          type: "input",
          name: "name",
          message: "What should it be called? (you can add a path here like `dir/ExampleButton`)",
          default: "ExampleButton"
        }
      ],
      actions: [
        {
          type: "add",
          path: `${basePath}/\.tsx`,
          templateFile: `${cwd}/generators/ClassComponent/templates/component.tsx.hbs`,
          abortOnFail: true
        },
        {
          type: "add",
          path: `${basePath}/\.style.ts`,
          templateFile: `${cwd}/generators/Shared/templates/component.style.ts.hbs`,
          abortOnFail: true
        },
        {
          type: "add",
          path: `${basePath}/index.ts`,
          templateFile: `${cwd}/generators/Shared/templates/index.ts.hbs`,
          abortOnFail: true
        }
      ]
    }
  }
}

Customize the templates to suit your project needs. This is an example of a component.tsx.hbs template for Plop.js:

import React from "react";
import { Container } from './{{ pascalCase name }}.style';

function {{ pascalCase name }}() {
return (
  <div>
  
  </div>
  );
}

export default {{ pascalCase name }};

Then you can generate components: Terminal recording

This is a simple Plop example for React file generation. Customize it to fit your project! 😊

Subscribe to receive our posts first hand!

Code1 logo