Select Page

How to create reusable form component with reusable inputs

by | Oct 24, 2023

Introduction

Creating a reusable form component with reusable inputs in React can significantly streamline your web development process.

This tutorial will guide you through the steps of building such a component. We will create a form component with reusable input fields, demonstrating best practices for code reusability and maintainability.

Create new file for the reusable input

We’ll begin by creating reusable input component. In this example, we’ll create one input component, this component will take every attributes as props and will be used multiple times . This component will encapsulate the input fields’ behavior.

Create a new folder named “components” in the src directory and inside it, create one file: ReusableInput.js.

import React from 'react';

const ReusableInput = ({ label, value, onChange, type, ...props }) => {
  return (
    <div>
      <label>{label}</label>
      <input type={type} value={value} onChange={onChange} {...props} />
    </div>
  );
};

export default ReusableInput;

This component accept label, value,type and onChange as props, making it versatile for different input fields.

Creating a Reusable Form Component

Now, let’s create a reusable form component that will use our input components. Create a new file named ReusableForm.js in the “components” folder.

import React, { useState } from 'react';
import ReusableInput from './ReusableInput';

const ReusableForm = () => {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
  });

  const handleInputChange = (fieldName) => (e) => {
    setFormData({ ...formData, [fieldName]: e.target.value });
  };

  const handleSubmit = () => {
    // Handle form submission here
    // You can access the form data using formData
  };

  return (
    <div>
      <h2>Reusable Form</h2>
      <ReusableInput
        type="text"
        label="Name"
        value={formData.name}
        onChange={handleInputChange('name')}
      />
      <ReusableInput
        type="email"
        label="Email"
        value={formData.email}
        onChange={handleInputChange('email')}
      />
      <button onClick={handleSubmit}>Submit</button>
    </div>
  );
};

export default ReusableForm;

In this component, we have two input fields, “Name” and “Email,” each using the same reusable input component. The handleInputChange function updates the state when the input value changes, and the handleSubmit function can be customized to handle form submission.

Using the Reusable Form Component

Now that we’ve created the reusable form component, you can use it in your application. Open the src/App.js file and import and use the ReusableForm component:

import React from 'react';
import './App.css';
import ReusableForm from './components/ReusableForm';

function App() {
  return (
    <div className="App">
      <ReusableForm />
    </div>
  );
}

export default App;

You can now run your React application by executing npm start in your project’s root directory.
Open your browser, and you’ll see your reusable form component in action. You can enter text and email addresses into the input fields and submit the form.

How to make the Form reusable and pass everything from props?

import React from 'react';
import ReusableInput from './ReusableInput';

const ReusableForm = (props) => {
  return (
    <div>
      <h2>Reusable Form</h2>
      <ReusableInput
        type="text"
        label="Name"
        value={props.formData.name}
        onChange={props.handleInputChange('name')}
      />
      <ReusableInput
        type="email"
        label="Email"
        value={props.formData.email}
        onChange={props.handleInputChange('email')}
      />
      <button onClick={props.handleSubmit}>Submit</button>
    </div>
  );
};

export default ReusableForm;
import React, { useState } from 'react';
import './App.css';
import ReusableForm from './components/ReusableForm';

function App() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
  });

  const handleInputChange = (fieldName) => (e) => {
    setFormData({ ...formData, [fieldName]: e.target.value });
  };

  const handleSubmit = () => {
    // Handle form submission here
    // You can access the form data using formData
  };

  return (
    <div className="App">
      <ReusableForm formData={formData}
 handleInputChange={handleInputChange} 
handleSubmit={handleSubmit} />
    </div>
  );
}

export default App;

Why we should create and use reusable components in React?

Using reusable components in software development, including web development, offers several benefits, making it a best practice for creating maintainable, efficient, and scalable applications. Here are some key reasons why you should use reusable components:

  1. Code Reusability: Reusable components allow you to write code once and use it in multiple places within your application.
    This saves time and effort and reduces the likelihood of duplicating code.
  2. Maintenance: When you have a bug or need to make changes to a particular feature or UI element, you can update the reusable component in one place, and those changes will propagate throughout your application.
    This reduces the risk of introducing bugs while making updates.
  3. Consistency: Reusable components help maintain a consistent look and behavior across your application.
    Since the same component is used throughout, you can ensure that your UI elements follow the same design guidelines and functionality.
  4. Scalability: As your application grows, it becomes increasingly important to manage complexity. Reusable components enable you to break down your application into manageable, modular pieces.
    This makes it easier to scale and add new features without compromising the structure of your code.
  5. Simplified Testing: When you have reusable components, you can test them once and be confident that they will work as expected wherever you use them.
    This simplifies the testing process and reduces the testing effort required.
  6. Improved Collaboration: Reusable components facilitate collaboration among development teams.
    Teams can work on individual components in parallel, and as long as they adhere to the component’s API, integration becomes more straightforward.
  7. Faster Development: Building on existing components accelerates the development process. Instead of creating everything from scratch, you can leverage pre-built components, saving both development time and resources.
  8. Easier Debugging: When an issue arises in a reusable component, it can be easier to isolate and debug, as you only need to focus on the component itself. This can lead to faster issue resolution.
  9. Separation of Concerns: Reusable components encourage a separation of concerns in your codebase.
    Each component should ideally have a single responsibility, making your code more maintainable and easier to understand.
  10. Better Documentation: Reusable components come with clear APIs and documentation, making it easier for developers to understand how to use them and what to expect from them.
  11. Community and Open Source: In many development communities, open-source libraries and component ecosystems thrive.
    You can benefit from the work of others and contribute to the community by creating and sharing your own reusable components.
  12. Future-Proofing: Reusable components make it easier to adapt to changes in technology or design trends.
    When an update or a migration is needed, you can focus on the components rather than having to refactor an entire application.

Conclusion

Creating a reusable form component with reusable input components in React can save you time and effort in web development projects.

This tutorial demonstrated how to create custom input components, a reusable form component, and integrate them into your React application. With this approach, you can easily maintain and scale your forms while keeping your code clean and organized.

Want to learn how to create reusable modal? Click Here.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Looking For Something?

Follow Us

Related Articles

How to Create Custom Hooks in React: Simplified Guide with Examples

How to Create Custom Hooks in React: Simplified Guide with Examples

Heard about custom hooks but not sure how to harness their power? In this blog post, we’ll delve into the wonderful world of custom hooks in React, breaking down what they are, how to create them, and why they’re a game-changer for your projects. What Are Custom...

Understanding Layouts in React

Understanding Layouts in React

If you're someone who works with React, you might think you know what a layout is. But, do you really? React, a popular JavaScript library for building user interfaces, employs the concept of layouts to organize and structure web applications. Despite its widespread...

Subscribe To Our Newsletter

Subscribe To Our Newsletter

Join our mailing list to receive the latest news and updates from our team.

You have Successfully Subscribed!