Next, we are going to completely gut out every JavaScript script inside our src/index.html. First, remove all the dependency <script> tags, such as React, ReactDOM, Babel, and bcryptjs. Then, we will use yarn to install them instead.
$ yarn add react react-dom bcryptjs
$ yarn add @babel/core @babel/preset-react @babel/preset-env @babel/plugin-proposal-class-properties --dev
We can now use these packages by importing them, just as we did with our back-end code.
Next, we will split our JavaScript code within index.html into separate modules. We will create:
- A utils directory to hold utility functions that can be re-used.
- A components directory to hold all our components.
- index.jsx as the entry point. This will be where we import the overall App component and render it onto the DOM with ReactDOM.render().
Run the following on your terminal:
$ mkdir -p \
src/utils/validator \
src/utils/register \
src/components/input \
src/components/button \
src/components/Registration-form
$ touch \
src/index.jsx \
src/utils/validator/index.js \
src/utils/register/index.js \
src/components/input/index.jsx \
src/components/button/index.jsx \
src/components/Registration-form/index.jsx
First, let's move the validator object from the src/index.html file into src/utils/validator/index.js and export it.
const validator = {
email: (email) => /\S+@\S+\.\S+/.test(email),
password: (password) => password.length > 11 && password.length < 48
}
export default validator;
Do the same for the register function. Then, extract each component into its own index.jsx. For instance, src/components/button/index.jsx would contain the code below.
import React from 'react';
function Button(props) {
return <button disabled={props.disabled}>{props.title}</button>
}
export default Button;
And src/components/input/index.jsx would look like this:
import React from 'react';
function getIndicatorColor (state) { ... }
function Input (props) { ... }
export {
Input as default,
getIndicatorColor,
}
For the RegistrationForm component, which has external dependencies, we can import it at the top of the module:
import React from 'react';
import bcrypt from 'bcryptjs';
import { validator } from '../../utils';
import register from '../../utils/register';
import Button from '../button/index.jsx';
import Input from '../input/index.jsx';
class RegistrationForm extends React.Component { ... }
export default RegistrationForm;
Finally, in our src/index.jsx, import the RegistrationForm component and render it onto the DOM:
import React from 'react';
import ReactDOM from 'react-dom';
import RegistrationForm from './components/Registration-form/index.jsx';
ReactDOM.render(<RegistrationForm />, document.getElementById('renderTarget'));