Jason Thomas

Jason Thomas

1568794907

How to build a dynamic form in React using Hooks

An example of fully dynamic form rendering with Hooks and some other tricks

Hooks were added to React 16.8 and increased the number of features that can be used in functional components. The 2 main additions are lifecycle methods and state management.

The two hooks to achieve that are useEffect() and useState(). From these two I will use the latter to showcase state management in a dynamic form.

Let’s start by creating the first building block of our dynamic form, the Input.js component:

import React from "react";

import classes from “./Input.module.css”;

const Input = ({
text,
type,
placeholder = text,
handleChange,
name,
id = name,
required = false
}) => {
return (
<>
<label htmlFor={id}>{text}</label>
<input
className={classes.input}
required={required}
name={name}
id={id}
type={type}
placeholder={placeholder}
onChange={handleChange}
/>
</>
);
};

export default Input;

We are using couple of things here:

  • Css modules for styling. Thanks to the new react version no webpack configuration is necessary, React will recognize css modules if they are created with the module.css tag
  • Props destructuring for visibility and control over what props are we sending to our Input.js.
  • Setting default props, for instance placeholder = text. That means if we are not passing down a placeholder prop the text will be used as a default. Another benefit of props destructuring.

Secondly we should create our custom Button.js component:

import React from “react”;

import classes from “./Button.module.css”;

const Button = ({ text, clicked, buttonType }) => {
return (
<>
<button onClick={clicked} className={${classes.button} ${classes[buttonType]}}>
{text}
</button>
</>
);
};

export default Button;

Another trick we are using here:

  • We are passing the buttonType down, so that we can create custom styles for different type of buttons we want to have in the application, while classes.button provides the basic style. As Input.js, this component can also be further customized.

Now we have our Input.js and Button.js components, but before putting them to use we should create a file that will hold our input fields and form structures. Create the following file:

const fields = {
firstName: { type: “text”, name: “firstName”, text: “First Name”, placeholder: ‘Jack’, required: true },
lastName: { type: “text”, name: “lastName”, text: “Last Name”, placeholder: ‘Doe’, required: true },
email: { type: “email”, name: “email”, text: “Email”, placeholder: ‘jack@mail.com’, required: true },
addressLine: { type: “text”, name: “addressLine”, text: “Address Line”, placeholder: ‘Awesome str 9’, required: true },
postalCode: { type: “text”, name: “postalCode”, text: “Postal Code”, placeholder: ‘12345’, required: true },
city: { type: “text”, name: “city”, text: “City”, placeholder: ‘Gothenburg’, required: true },
state: { type: “text”, name: “state”, text: “State”, placeholder: ‘Gotaland’, required: true },
dob: { type: “date”, name: “dob”, text: “Date of Birth”, required: true },
password: { type: “password”, name: “password”, text: “Password”, required: true },
passwordConfrimation: { type: “password”, name: “passwordConfirmation”, text: “Password Confirmation”, required: true }
}

export const registerForm = [
fields.firstName,
fields.lastName,
fields.email,
fields.addressLine,
fields.postalCode,
fields.state,
fields.dob,
fields.password,
fields.passwordConfrimation
];

export const loginForm = [
fields.email,
fields.password
];

The fields object holds all possible field that we can add to our forms. This can be easily updated, new fields can be added or the current ones can be customized. I also added a registerForm and loginForm examples. We just need to export these arrays so that we can create the dynamic forms!

Next we will create the Form.js file where we will first use the useState() hook to manage the information in our form, and will also call all of those components we created to action!

import React from “react”;

import Input from “…/Input/Input”;
import Button from “…/Button/Button”;
import classes from “./Form.module.css”;

const Form = ({
formStructure,
formData,
setFormData,
formTitle,
buttonText,
onSubmit
}) => {
const handleChange = event => {
const formDataCopy = { …formData };
formDataCopy[event.target.name] = event.target.value;
setFormData(formDataCopy);
};
return (
<form className={classes.form} onSubmit={onSubmit}>
<h2>{formTitle}</h2>
{formStructure.map(f => (
<Input
key={f.name}
type={f.type}
name={f.name}
id={f.id}
text={f.text}
handleChange={handleChange}
placeholder={f.placeholder}
required={f.required}
/>
))}
<Button buttonType=‘primary’ text={buttonText} />
</form>
);
};

export default Form;

To break down what is happening here:

  • The formStructure prop is the array we export from formElements.js file, in this example either registerForm or loginForm. Since these are arrays we can use the map function to iterate through them and render the Input.js component. These objects hold all the information necessary for our Input.js component, so we just need to pass them down.
  • formTitle and buttonText are additional information either used in the Form.js itself or passed down to our custom Button.js component.
  • The last bit is the handleChange() function where we use useState() hook! Both formData and setFormData comes from the hook, however the state is not used in this form, but in the container that renders the form.
  • In the function we copy the formData using the spread operator. This is very important because the useState() hook — as opposed to this.setState() function does not automatically merge the state, but replaces it! Therefore we always have to preserve the previous state.
  • After copying we can set the object either create a new key or update the existing one by using this syntax: formDataCopy[event.target.name] = event.target.value

That is the basic skeleton for our dynamic form! Now we need a container to render it, where we have the actual logic: managing the state and performing the necessary side effects. I am going to show you an example for rendering registration and login form in a common container I call AuthenticationForm.js :

import React, { useState } from “react”;
import { connect } from “react-redux”;
import { withRouter } from “react-router-dom”;

import Form from “…/…/UI/Form/Form”;
import {
registerUser,
signInUser
} from “…/…/store/config/redux-token-auth-config”;

const AuthenticationForm = props => {
const [formData, setFormData] = useState({});
const action = data => {
switch (props.action) {
case “register”:
return props.registerUser(data);
case “login”:
return props.signInUser(data);
default:
console.log(“Something went wrong”);
}
};
const onSubmit = e => {
e.preventDefault();
action(formData)
.then(() => {
props.history.push(“/”);
})
.catch(error => {
console.log(error);
});
};

return (
<Form
onSubmit={onSubmit}
formTitle={props.formTitle}
setFormData={setFormData}
formStructure={props.formStructure}
formData={formData}
buttonText={props.buttonText}
/>
);
};

export default connect(
null,
{ registerUser, signInUser }
)(withRouter(AuthenticationForm));

You could create two separate components for registration and login forms, but there will be very little difference between them. In the name of re-usability and DRY code we will it in one container. So what is happening here?

  • const [formData, setFormData] = useState({}) is how we create our initial formData state, which is empty in the beginning, and setFormData() will be the function that will update that state.
  • The action function takes that formData and performs the selected function, which is either registerUser() or signInUser(). This is an authentication solution coming from redux-token-auth because we are using Rails as the API with devise-token-auth. During the function execution we use a switch statement where we can dynamically set that function based on the props we receive.
  • The last function is the onSubmit(), where we perform our action() function, making a HTTP POST request to our API. Upon success reroute to root using the react-router-dom package or catch errors (more error handling functions can be performed there).
  • As a side-note: the withRouter hoc is necessary because we are using the render() method in the <Route /> component (will be shown later), instead of the component prop. Because of that the history object is not available by default, we need to wrap the component with withRouter if we want to use it.

Finally we need to render the AuthenticationForm.js somewhere. I use the react-router-dom package to render the forms on different URLs in App.js:

import React, { lazy, Suspense } from “react”;
import { Route, Switch } from “react-router-dom”;

import Header from “./components/Header/Header”;
import { registerForm, loginForm } from “./UI/Form/formElements”;

const Fruits = lazy(() => import(“./components/Fruits/Fruits”));
const AuthenticationForm = lazy(() =>
import(“./components/AuthenticationForm/AuthenticationForm”)
);

const App = () => {
return (
<div>
<Header />
<Suspense fallback={<div>Loading …</div>}>
<Switch>
<Route exact path=“/” render={() => <Fruits />} />
<Route
exact
path=“/register”
render={() => (
<AuthenticationForm
action=“register”
formTitle=“Registration”
buttonText=“Register”
formStructure={registerForm}
/>
)}
/>
<Route
exact
path=“/login”
render={() => (
<AuthenticationForm
action=“login”
formTitle=“Login”
buttonText=“Login”
formStructure={loginForm}
/>
)}
/>
</Switch>
</Suspense>
</div>
);
};

export default App;

The loop is completed:

  • We import our registerForm and loginForm arrays from our formElements.js file which will create our dynamic forms.
  • We set the action prop which will determine which function will be used, registerUser() or signInUser().
  • We add the formTitle and buttonText to the forms.

The basic skeleton is ready for further use, after the little lengthy setup it will be much quicker and DRYer to create new forms in our application and without the need for Class components!

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

☞ Top 10 Custom React Hooks you Should Have in Your Toolbox

☞ How to Replace Redux with React Hooks and the Context API

☞ The Definitive React Hooks Cheatsheet

Originally published by Greg Kallai at https://medium.com

#reactjs #javascript #web-development

What is GEEK

Buddha Community

How to build a dynamic form in React using Hooks
Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

What are hooks in React JS? - INFO AT ONE

In this article, you will learn what are hooks in React JS? and when to use react hooks? React JS is developed by Facebook in the year 2013. There are many students and the new developers who have confusion between react and hooks in react. Well, it is not different, react is a programming language and hooks is a function which is used in react programming language.
Read More:- https://infoatone.com/what-are-hooks-in-react-js/

#react #hooks in react #react hooks example #react js projects for beginners #what are hooks in react js? #when to use react hooks

Hayden Slater

1599277908

Validating React Forms With React-Hook-Form

Validating inputs is very often required. For example, when you want to make sure two passwords inputs are the same, an email input should in fact be an email or that the input is not too long. This is can be easily done using React Hook From. In this article, I will show you how.

Required Fields

The most simple, yet very common, validation is to make sure that an input component contains input from the user. React Hook Form basic concept is to register input tags to the form by passing register() to the tag’s ref attribute. As we can see here:

#react-native #react #react-hook-form #react-hook

Seamus  Quitzon

Seamus Quitzon

1598954760

Build a Contact Form with React Hooks and PHP

A while ago I wrote an article about creating a contact form using React and PHP. Many people found it interesting. So, here I am writing an updated version of that article.

Check out the article about creating a contact form with React and PHP:

Hooks are a new addition in React and we are going to re-create the contact form using React Hooks.

Prerequisites? Not really!

Same as the previous project. This tutorial is beginners friendly. You don’t have to be an expert in Javascript, React, or PHP but I won’t go into basic details like installing React and setting up the project.

I assume you already have an up and running React project. We will focus on creating the component.

Creating the component

If you have a component folder in your project please go ahead and create a ‘Form’ folder inside it. It is up to you to decide where the component should live. Once you created the folder let’s create the ‘index.js’ file.

#react #reactphp #react-php-contac-form #contact-form #react-hook

Erna  Herzog

Erna Herzog

1626748440

Build a React Accordion from Scratch Using React Hooks and No Extra Dependencies

Follow these step-by-step instructions to create an animated accordion component in React.js using React Hooks and CSS.

🗂 DOWNLOADS 🗂

https://gum.co/AEeem

🔗 HELPFUL RESOURCES 🔗

React DOM Elements: https://reactjs.org/docs/dom-elements.html

Overview of dangerouslySetInnerHTML: https://react-cn.github.io/react/tips/dangerously-set-inner-html.html

How to prevent XSS attacks when using dangerouslySetInnerHTML in React: https://dev.to/jam3/how-to-prevent-xss-attacks-when-using-dangerouslysetinnerhtml-in-react-1464

Hooks API Reference: https://reactjs.org/docs/hooks-reference.html

Visual Studio Code: https://code.visualstudio.com/

#react #react hooks #react accordion #css #react.js