React Form and Array example

In this tutorial, we’re gonna build a simple React Application that shows an Array of items submitted from a Form.

Related Posts:
React Hello World example
React Simple Data Binding example

I. Technologies

– React 16
– NodeJs 6.11.2
– NPM 3.10.10
– Yarn 1.5.1
– Babel 6.24.1

II. Practice

1. Goal

We will build a React Application that can receive data from a form submission, then display them as a list:

react-form-array-example-result

2. Project Structure

react-example-project-structure

3. Step by Step

3.0 Set up Environment

We need NodeJs, Yarn and Babel to compile and run this example.
Please visit Set up Environment for step by step.

3.1 Set up Project folder

Create folder for BindData project, then make subfolders and subfiles like this:
react-example-create-folder

3.2 Dependency

Open package.json, write these lines for project information and dependency:


{
  "name": "form-array",
  "version": "1.0.0",
  "main": "index.js",
  "author": "JavaSampleApproach",
  "license": "MIT",
  "dependencies": {
    "babel-preset-env": "1.5.2",
    "babel-preset-react": "6.24.1"
  }
}

3.3 index.html

This is the default HTML file that appears in the browser when we invokes our application.
We also use this HTML file to embed React files and reference to our javascript app.js.

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>JSA React Demo</title>
</head>

<body>
    <div id="app"></div>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="./scripts/app.js"></script>
</body>

</html>

div tag with id="app" for rendering template in the next step.

3.4 app.js


const app = {
    title: 'Java Sample Approach',
    categories: []
}

const removeAll = () => {
    app.categories = [];
    renderApp();
}

const submit = (e) => {
    e.preventDefault();

    const data = e.target.elements.data.value;
    if (data) {
        console.log(data);
        app.categories.push(data);
        e.target.elements.data.value = '';
        renderApp();
    }
}

const appRoot = document.getElementById('app');
const renderApp = () => {
    const template = (
        <div>
            <h2>{app.title}</h2>
            <p>{app.categories.length > 0 ? 'Categories:' : 'No category!'}</p>
            <ol>
                {
                    app.categories.map((category) =>
                        <li key={category}>{category}</li>
                    )
                }
            </ol>

            <form onSubmit={submit}>
                <input type="text" name="data" />
                <button>Add</button>
            </form>

            <br />
            <button onClick={removeAll}>Remove All</button>
        </div>
    );

    ReactDOM.render(template, appRoot);
};

renderApp();

– Firstly, we create a Form element with onSubmit event that invokes submit() function for submission, data is the element name that we will use for getting value inside submit() function:

<form onSubmit={submit}>
    <input type="text" name="data" />
    <button>Add</button>
</form>

– Inside submit() function with event as input parameter:
+ We call preventDefault() event method to make default action that belongs to the event not occur.
+ We get data from form submission by event.target.elements.data.value.
+ Then we add the data value to categories array using array.push(value).
+ We also need to re-render template for updating UI.


const submit = (e) => {
    e.preventDefault();

    const data = e.target.elements.data.value;
    if (data) {
        app.categories.push(data);
        e.target.elements.data.value = '';
        renderApp();
    }
}

– Use map() method to iterate array items:


app.categories.map((category) =>
    
  • {category}
  • )

    3.5 Run & Check result

    – Point cmd to project folder, then run cmd: yarn install.
    node_modules folder and yarn.lock file now appear in our project folder:

    react-example-after-yarn-install

    – Run cmd: babel src/app.js --out-file=public/scripts/app.js --presets=env,react --watch
    Now, a new app.js file appear in public/scripts folder, code insides this file was generated automatically (and also update automatically whenever we modify and save src/app.js).

    – Open new cmd, point to Project folder, run cmd: live-server public.
    Result in Browser:

    react-form-array-example-result

    III. Source code

    ReactForm



    By grokonez | March 27, 2018.

    Last updated on May 4, 2021.



    Related Posts


    Got Something To Say:

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

    *