Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to display form data in table using ReactJS

Getting Started

ReactJS is a powerful JavaScript library for building user interfaces, especially for single page applications. In this tutorial, we're going to learn about displaying form data in a table using ReactJS—it's like creating a dynamic list where we can add, view, and manipulate items (form data).

Form Data and How ReactJS Handles It

Before we dive in, let's talk about form data. When you fill out a form on a website, the information you enter is the form data. In ReactJS, form data is usually stored in the component's state and can be passed around the application using props.

State is like a personal notebook for each component, where it can jot down important details to remember. Props, on the other hand, are like messengers delivering these details to other components.

Setting Up Our React Application

First things first, we need to set up a new React application. You can do this by using Create React App, a tool that sets up a new React project with a good default configuration. In your terminal, type:

npx create-react-app form-data-table

This will create a new directory called form-data-table with a fresh React app.

Creating the Form Component

Now, let's create a new component for our form. This component will handle the user input and update the state accordingly. Think of it as a virtual post office: it collects the information (letters) and then sends it to the proper location.

In your src directory, create a new file called Form.js and add the following code:

import React, { Component } from 'react';

class Form extends Component {
  constructor(props) {
    super(props);

    this.initialState = {
      name: '',
      email: '',
    };

    this.state = this.initialState;
  }

  handleChange = (event) => {
    const { name, value } = event.target;

    this.setState({
      [name]: value,
    });
  }

  submitForm = () => {
    this.props.handleSubmit(this.state);
    this.setState(this.initialState);
  }

  render() {
    return (
      <form>
        <label>Name</label>
        <input type="text" name="name" value={this.state.name} onChange={this.handleChange} />
        <label>Email</label>
        <input type="text" name="email" value={this.state.email} onChange={this.handleChange} />
        <input type="button" value="Submit" onClick={this.submitForm} />
      </form>
    );
  }
}

export default Form;

This code creates a new class component with a form. The form has two fields: name and email, and a Submit button. When a user types into the input fields, the handleChange function is called, updating the state with the new values. When the Submit button is clicked, the submitForm function is called, passing the current state to the parent component and resetting the form.

Creating the Table Component

Next, we will create a table to display the data. In the src directory, create a new file called Table.js and add the following code:

import React, { Component } from 'react';

class Table extends Component {
  render() {
    const { data } = this.props;

    return (
      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Email</th>
          </tr>
        </thead>
        <tbody>
          {data.map((row, index) => (
            <tr key={index}>
              <td>{row.name}</td>
              <td>{row.email}</td>
            </tr>
          ))}
        </tbody>
      </table>
    );
  }
}

export default Table;

This component receives the form data as props and maps over it to create a new table row for each item. It's like a notice board where each data item gets its own space.

Putting it All Together

Finally, we need to bring these two components together. In your App.js file, replace the existing code with:

import React, { Component } from 'react';
import Table from './Table';
import Form from './Form';

class App extends Component {
  state = {
    data: [],
  };

  removeData = (index) => {
    const { data } = this.state;

    this.setState({
      data: data.filter((data, i) => {
        return i !== index;
      }),
    });
  }

  handleSubmit = (formData) => {
    this.setState({ data: [...this.state.data, formData] });
  }

  render() {
    return (
      <div className="container">
        <Table data={this.state.data} removeData={this.removeData} />
        <Form handleSubmit={this.handleSubmit} />
      </div>
    );
  }
}

export default App;

This App component maintains the application state which includes the form data. It passes down the handleSubmit function to the Form component and the form data to the Table component.

Conclusion: The Art of Data Display

ReactJS provides an efficient and intuitive way to organize and manipulate data. It's like a master artist, knowing not only how to create beautiful pieces (components), but also how to arrange them in a way that's pleasing and easy to understand. By breaking down our application into smaller components, we're able to maintain a clear separation of concerns and a structured codebase.

Remember, this is just the tip of the iceberg when it comes to what ReactJS can do. There's a world of possibilities out there, waiting for you to explore. Happy coding!