How to work with client scripts, JavaScript in particular.
This article explains how to work with client scripts, especially JavaScript, and how to use React, Redux, webpack and forms validation. All client scripts are located under the \Src\Litium.Accelerator.Mvc\Client\Scripts folder.
Before you start
Please read these articles to make sure you have the right tools and understanding of how files are structured in Litium Accelerator.
JavaScript
All JavaScript codes should be written in ES6, as a module. Litium Accelerator has been built to include all of the build script polyfill, to make sure the ES6 code works on all types of browsers.
JavaScript files are located under the Litium.Accelerator.Mvc\Client\Scripts\ folder. It includes:
- React components
- Redux's actions and reducers
- Services like HTTP and translation
- Entry point index.js
UI components are implemented as "thin" as possible in React. This means that even though Litium Accelerator is shipped with React, it is not locked to this library. The presentation layer can be replaced by any other UI library or framework. We still have Redux's actions and reducers, and services that can be re-used.
React
All UI components are implemented in React, as presentational and container components. To understand the difference between them, please look here.
If you are new to React, begin with this tutorial on the official website: https://reactjs.org/tutorial/tutorial.html
Redux
If you are new to Redux begin here: https://redux.js.org/introduction/getting-started
Form validation
Yup is used for form validation, for example on the Checkout and My Page pages. Yup is a JavaScript object schema validator and object parser. To validate a person data object, for example, we define a schema:
const personSchema = object().shape({
phone: string().required(translate(`validation.required`)),
email: string().required(translate(`validation.required`)).email(translate(`validation.email`)),
lastName: string().required(translate(`validation.required`)),
firstName: string().required(translate(`validation.required`))
});
Phone, email, lastName and firstName are declared as mandatory fields. Each field has a validation message, which is translated by the translate function. The email field has an additional validation, which makes sure that the string has the right email format.
To validate an object, call the validate function:
personSchema.validate(person)
The validate function will return a promise object that is fulfilled if the person object is valid, or rejected with a ValidationError if the person object is invalid. Check PersonList.container.js and Checkout.container.js for reference.